(function(f,sf){typeof exports=="object"&&typeof module<"u"?sf(exports):typeof define=="function"&&define.amd?define(["exports"],sf):(f=typeof globalThis<"u"?globalThis:f||self,sf(f.threepipe={}))})(this,(function(f){"use strict";/**
 * @license
 * threepipe v0.5.1
 * Copyright 2022-2026 repalash <palash@shaders.app>
 * Apache-2.0 License
 * See ./dependencies.txt for bundled third-party dependencies and licenses.
 *//**
 * @license
 * Copyright 2010-2023 Three.js Authors
 * SPDX-License-Identifier: MIT
 */var La,Fs,Fl,Wr,Eo,Hh,Gl,Oa,tr,Mo,Wh,qh;const zl={ROTATE:0,DOLLY:1,PAN:2},Vl={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},yP=0,vb=1,vP=2,Kg=1,_P=2,Yr=3,fs=0,Rn=1,Zi=2,gn=0,xr=1,rf=2,af=3,of=4,ir=5,Sr=100,_b=101,bb=102,wb=103,Cb=104,Jg=200,Zg=201,eA=202,tA=203,Hl=204,Ql=205,iA=206,nA=207,sA=208,rA=209,xb=210,Yh=211,$h=212,jl=213,Wl=214,Sb=0,Eb=1,Mb=2,ql=3,Tb=4,Ib=5,Pb=6,Db=7,Xl=0,bP=1,wP=2,$r=0,Rb=1,Bb=2,Lb=3,aA=4,Ob=5,Ub=6,CP=7,Fb="attached",xP="detached",Kh=300,Kr=301,Io=302,Jr=303,lf=304,Yl=306,Bn=1e3,ui=1001,Zr=1002,pi=1003,Jh=1004,Na=1005,st=1006,Po=1007,Ln=1008,Nb=1008,Wt=1009,kb=1010,Gb=1011,oA=1012,lA=1013,ea=1014,zt=1015,$t=1016,cA=1017,hA=1018,$l=1020,SP=35902,EP=1021,MP=1022,Kt=1023,TP=1024,IP=1025,Do=1026,Zh=1027,ka=1028,zb=1029,Kl=1030,Vb=1031,Hb=1033,cf=33776,uA=33777,dA=33778,hf=33779,fA=35840,Qb=35841,pA=35842,jb=35843,mA=36196,gA=37492,AA=37496,yA=37808,Wb=37809,qb=37810,Xb=37811,uf=37812,Yb=37813,$b=37814,Kb=37815,Jb=37816,Zb=37817,ew=37818,tw=37819,iw=37820,nw=37821,df=36492,sw=36494,rw=36495,PP=36283,aw=36284,ow=36285,lw=36286,vA=2200,_A=2201,DP=2202,Jl=2300,Ro=2301,bA=2302,Zl=2400,ec=2401,ff=2402,wA=2500,cw=2501,RP=0,hw=1,CA=2,xA=3200,tc=3201,ks=0,uw=1,si="",vt="srgb",Dt="srgb-linear",eu="display-p3",tu="display-p3-linear",Gs="rgbm-16",pf="linear",bi="srgb",mf="rec709",gf="p3",ta=7680,SA=519,BP=512,LP=513,OP=514,dw=515,UP=516,FP=517,NP=518,kP=519,Af=35044,GP="100",EA="300 es",ia=2e3,yf=2001,fw=3e3,vf=3001;class wi{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const n=this._listeners[e];if(n!==void 0){const s=n.indexOf(t);s!==-1&&n.splice(s,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const i=this._listeners[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let s=0,a=n.length;s<a;s++)n[s].call(this,e);e.target=null}}}const zn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let pw=1234567;const Bo=Math.PI/180,ic=180/Math.PI;function Ss(){const r=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(zn[r&255]+zn[r>>8&255]+zn[r>>16&255]+zn[r>>24&255]+"-"+zn[e&255]+zn[e>>8&255]+"-"+zn[e>>16&15|64]+zn[e>>24&255]+"-"+zn[t&63|128]+zn[t>>8&255]+"-"+zn[t>>16&255]+zn[t>>24&255]+zn[i&255]+zn[i>>8&255]+zn[i>>16&255]+zn[i>>24&255]).toLowerCase()}function zi(r,e,t){return Math.max(e,Math.min(t,r))}function MA(r,e){return(r%e+e)%e}function zP(r,e,t,i,n){return i+(r-e)*(n-i)/(t-e)}function VP(r,e,t){return r!==e?(t-r)/(e-r):0}function iu(r,e,t){return(1-t)*r+t*e}function HP(r,e,t,i){return iu(r,e,1-Math.exp(-t*i))}function QP(r,e=1){return e-Math.abs(MA(r,e*2)-e)}function jP(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*(3-2*r))}function WP(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*r*(r*(r*6-15)+10))}function qP(r,e){return r+Math.floor(Math.random()*(e-r+1))}function XP(r,e){return r+Math.random()*(e-r)}function YP(r){return r*(.5-Math.random())}function $P(r){r!==void 0&&(pw=r);let e=pw+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function KP(r){return r*Bo}function JP(r){return r*ic}function ZP(r){return(r&r-1)===0&&r!==0}function eD(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function tD(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function iD(r,e,t,i,n){const s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(n){case"XYX":r.set(o*h,l*u,l*d,o*c);break;case"YZY":r.set(l*d,o*h,l*u,o*c);break;case"ZXZ":r.set(l*u,l*d,o*h,o*c);break;case"XZX":r.set(o*h,l*m,l*p,o*c);break;case"YXY":r.set(l*p,o*h,l*m,o*c);break;case"ZYZ":r.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function is(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function wt(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}const Ut={DEG2RAD:Bo,RAD2DEG:ic,generateUUID:Ss,clamp:zi,euclideanModulo:MA,mapLinear:zP,inverseLerp:VP,lerp:iu,damp:HP,pingpong:QP,smoothstep:jP,smootherstep:WP,randInt:qP,randFloat:XP,randFloatSpread:YP,seededRandom:$P,degToRad:KP,radToDeg:JP,isPowerOfTwo:ZP,ceilPowerOfTwo:eD,floorPowerOfTwo:tD,setQuaternionFromProperEuler:iD,normalize:wt,denormalize:is};class ${constructor(e=0,t=0){$.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,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(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(zi(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*i-a*n+e.x,this.y=s*n+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class mt{constructor(e,t,i,n,s,a,o,l,c){mt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,s,a,o,l,c)}set(e,t,i,n,s,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=o,h[3]=t,h[4]=s,h[5]=l,h[6]=i,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,s=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],h=i[4],u=i[7],d=i[2],p=i[5],m=i[8],A=n[0],g=n[3],y=n[6],_=n[1],v=n[4],b=n[7],T=n[2],E=n[5],M=n[8];return s[0]=a*A+o*_+l*T,s[3]=a*g+o*v+l*E,s[6]=a*y+o*b+l*M,s[1]=c*A+h*_+u*T,s[4]=c*g+h*v+u*E,s[7]=c*y+h*b+u*M,s[2]=d*A+p*_+m*T,s[5]=d*g+p*v+m*E,s[8]=d*y+p*b+m*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-i*s*h+i*o*l+n*s*c-n*a*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=h*a-o*c,d=o*l-h*s,p=c*s-a*l,m=t*u+i*d+n*p;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);const A=1/m;return e[0]=u*A,e[1]=(n*c-h*i)*A,e[2]=(o*i-n*a)*A,e[3]=d*A,e[4]=(h*t-n*l)*A,e[5]=(n*s-o*t)*A,e[6]=p*A,e[7]=(i*l-c*t)*A,e[8]=(a*t-i*s)*A,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,s,a,o){const l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-n*c,n*l,-n*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(TA.makeScale(e,t)),this}rotate(e){return this.premultiply(TA.makeRotation(-e)),this}translate(e,t){return this.premultiply(TA.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const TA=new mt;function mw(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}const nD={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function nc(r,e){return new nD[r](e)}function nu(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function sD(){const r=nu("canvas");return r.style.display="block",r}const gw={};function su(r){r in gw||(gw[r]=!0,console.warn(r))}const Aw=new mt().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),yw=new mt().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),_f={[Dt]:{transfer:pf,primaries:mf,toReference:r=>r,fromReference:r=>r},[vt]:{transfer:bi,primaries:mf,toReference:r=>r.convertSRGBToLinear(),fromReference:r=>r.convertLinearToSRGB()},[tu]:{transfer:pf,primaries:gf,toReference:r=>r.applyMatrix3(yw),fromReference:r=>r.applyMatrix3(Aw)},[eu]:{transfer:bi,primaries:gf,toReference:r=>r.convertSRGBToLinear().applyMatrix3(yw),fromReference:r=>r.applyMatrix3(Aw).convertLinearToSRGB()}},rD=new Set([Dt,tu]),Xt={enabled:!0,_workingColorSpace:Dt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(r){if(!rD.has(r))throw new Error(`Unsupported working color space, "${r}".`);this._workingColorSpace=r},convert:function(r,e,t){if(this.enabled===!1||e===t||!e||!t)return r;const i=_f[e].toReference,n=_f[t].fromReference;return n(i(r))},fromWorkingColorSpace:function(r,e){return this.convert(r,this._workingColorSpace,e)},toWorkingColorSpace:function(r,e){return this.convert(r,e,this._workingColorSpace)},getPrimaries:function(r){return _f[r].primaries},getTransfer:function(r){return r===si||r===Gs?pf:_f[r].transfer}};function sc(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function IA(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}let rc;class PA{static getDataURL(e,t=!1){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{rc===void 0&&(rc=nu("canvas")),rc.width=e.width,rc.height=e.height;const n=rc.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),i=rc}return!t&&(i.width>2048||i.height>2048)?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),i.toDataURL("image/jpeg",.6)):i.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=nu("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),s=n.data;for(let a=0;a<s.length;a++)s[a]=sc(s[a]/255)*255;return i.putImageData(n,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(sc(t[i]/255)*255):t[i]=sc(t[i]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let aD=0;class na{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:aD++}),this.uuid=Ss(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let s;if(Array.isArray(n)){s=[];for(let a=0,o=n.length;a<o;a++)n[a].isDataTexture?s.push(DA(n[a].image)):s.push(DA(n[a]))}else s=DA(n);i.url=s}return t||(e.images[this.uuid]=i),i}}function DA(r){if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap)return PA.getDataURL(r);if(r.data){let e=[];try{e=Array.from(r.data)}catch(t){t.message.includes("Invalid array length")?console.warn("Serializing large texture, might not be saved in JSON structure."):console.error(t),e=r.data}return{data:e,width:r.width,height:r.height,type:r.data.constructor.name}}else return r.url!==void 0?r.url:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let oD=0;class Rt extends wi{constructor(e=Rt.DEFAULT_IMAGE,t=Rt.DEFAULT_MAPPING,i=ui,n=ui,s=st,a=Ln,o=Kt,l=Wt,c=Rt.DEFAULT_ANISOTROPY,h=si){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:oD++}),this.uuid=Ss(),this.name="",this.source=new na(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new $(0,0),this.repeat=new $(1,1),this.center=new $(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new mt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof h=="string"?this.colorSpace=h:(su("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=h===vf?vt:si),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0,e instanceof ImageData&&e!==Rt.DEFAULT_IMAGE&&(this.needsUpdate=!0)}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=vw(this.userData,e.userData),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,encoding:this.colorSpace===vt?vf:fw,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=vw({},this.userData)),!t&&e.textures&&(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Kh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Bn:e.x=e.x-Math.floor(e.x);break;case ui:e.x=e.x<0?0:1;break;case Zr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Bn:e.y=e.y-Math.floor(e.y);break;case ui:e.y=e.y<0?0:1;break;case Zr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0,this.dispatchEvent({type:"update"}))}get encoding(){return su("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===vt?vf:fw}set encoding(e){su("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===vf?vt:si}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Rt.DEFAULT_IMAGE=null,Rt.DEFAULT_MAPPING=Kh,Rt.DEFAULT_ANISOTROPY=1;const lD=["appliedMaterials","uuid"];function vw(r,e){if(e)for(const t of Object.keys(e))lD.includes(t)||t.startsWith("__")||typeof r[t]=="function"||typeof e[t]=="function"||(r[t]=typeof e[t]=="object"?JSON.parse(JSON.stringify(e[t])):e[t]);return r}class rt{constructor(e=0,t=0,i=0,n=1){rt.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=n}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*n+a[12]*s,this.y=a[1]*t+a[5]*i+a[9]*n+a[13]*s,this.z=a[2]*t+a[6]*i+a[10]*n+a[14]*s,this.w=a[3]*t+a[7]*i+a[11]*n+a[15]*s,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,s;const l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],m=l[9],A=l[2],g=l[6],y=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-A)<.01&&Math.abs(m-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+A)<.1&&Math.abs(m+g)<.1&&Math.abs(c+p+y-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const v=(c+1)/2,b=(p+1)/2,T=(y+1)/2,E=(h+d)/4,M=(u+A)/4,S=(m+g)/4;return v>b&&v>T?v<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(v),n=E/i,s=M/i):b>T?b<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(b),i=E/n,s=S/n):T<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(T),i=M/s,n=S/s),this.set(i,n,s,t),this}let _=Math.sqrt((g-m)*(g-m)+(u-A)*(u-A)+(d-h)*(d-h));return Math.abs(_)<.001&&(_=1),this.x=(g-m)/_,this.y=(u-A)/_,this.z=(d-h)/_,this.w=Math.acos((c+p+y-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,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(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class _w extends wi{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new rt(0,0,e,t),this.scissorTest=!1,this.viewport=new rt(0,0,e,t);const n={width:e,height:t,depth:1};i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:st,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0,count:1},i);const s=new Rt(n,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace);s.flipY=!1,s.generateMipmaps=i.generateMipmaps,s.internalFormat=i.internalFormat,this.textures=[];const a=i.count;for(let o=0;o<a;o++)this.textures[o]=s.clone(),this.textures[o].isRenderTargetTexture=!0;this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.depthTexture=i.depthTexture,this.samples=i.samples}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let n=0,s=this.textures.length;n<s;n++)this.textures[n].image.width=e,this.textures[n].image.height=t,this.textures[n].image.depth=i;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let i=0,n=e.textures.length;i<n;i++)this.textures[i]=e.textures[i].clone(),this.textures[i].isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new na(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ps extends _w{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class bf extends Rt{constructor(e=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=pi,this.minFilter=pi,this.wrapR=ui,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class cD extends ps{constructor(e=1,t=1,i=1,n={}){super(e,t,n),this.isWebGLArrayRenderTarget=!0,this.depth=i,this.texture=new bf(null,e,t,i),this.texture.isRenderTargetTexture=!0}}class wf extends Rt{constructor(e=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=pi,this.minFilter=pi,this.wrapR=ui,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class hD extends ps{constructor(e=1,t=1,i=1,n={}){super(e,t,n),this.isWebGL3DRenderTarget=!0,this.depth=i,this.texture=new wf(null,e,t,i),this.texture.isRenderTargetTexture=!0}}class Qe{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,s,a,o){let l=i[n+0],c=i[n+1],h=i[n+2],u=i[n+3];const d=s[a+0],p=s[a+1],m=s[a+2],A=s[a+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=p,e[t+2]=m,e[t+3]=A;return}if(u!==A||l!==d||c!==p||h!==m){let g=1-o;const y=l*d+c*p+h*m+u*A,_=y>=0?1:-1,v=1-y*y;if(v>Number.EPSILON){const T=Math.sqrt(v),E=Math.atan2(T,y*_);g=Math.sin(g*E)/T,o=Math.sin(o*E)/T}const b=o*_;if(l=l*g+d*b,c=c*g+p*b,h=h*g+m*b,u=u*g+A*b,g===1-o){const T=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=T,c*=T,h*=T,u*=T}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,i,n,s,a){const o=i[n],l=i[n+1],c=i[n+2],h=i[n+3],u=s[a],d=s[a+1],p=s[a+2],m=s[a+3];return e[t]=o*m+h*u+l*p-c*d,e[t+1]=l*m+h*d+c*u-o*p,e[t+2]=c*m+h*p+o*d-l*u,e[t+3]=h*m-o*u-l*d-c*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,s=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),h=o(n/2),u=o(s/2),d=l(i/2),p=l(n/2),m=l(s/2);switch(a){case"XYZ":this._x=d*h*u+c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u-d*p*m;break;case"YXZ":this._x=d*h*u+c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u+d*p*m;break;case"ZXY":this._x=d*h*u-c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u-d*p*m;break;case"ZYX":this._x=d*h*u-c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u+d*p*m;break;case"YZX":this._x=d*h*u+c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u-d*p*m;break;case"XZY":this._x=d*h*u-c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u+d*p*m;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],s=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=i+o+u;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(s-c)*p,this._z=(a-n)*p}else if(i>o&&i>u){const p=2*Math.sqrt(1+i-o-u);this._w=(h-l)/p,this._x=.25*p,this._y=(n+a)/p,this._z=(s+c)/p}else if(o>u){const p=2*Math.sqrt(1+o-i-u);this._w=(s-c)/p,this._x=(n+a)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+u-i-o);this._w=(a-n)/p,this._x=(s+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<Number.EPSILON?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(zi(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+a*o+n*c-s*l,this._y=n*h+a*l+s*o-i*c,this._z=s*h+a*c+i*l-n*o,this._w=a*h-i*o-n*l-s*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,n=this._y,s=this._z,a=this._w;let o=a*e._w+i*e._x+n*e._y+s*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=i,this._y=n,this._z=s,this;const l=1-o*o;if(l<=Number.EPSILON){const p=1-t;return this._w=p*a+t*this._w,this._x=p*i+t*this._x,this._y=p*n+t*this._y,this._z=p*s+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,o),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=a*u+this._w*d,this._x=i*u+this._x*d,this._y=n*u+this._y*d,this._z=s*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class x{constructor(e=0,t=0,i=0){x.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(bw.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(bw.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*n,this.y=s[1]*t+s[4]*i+s[7]*n,this.z=s[2]*t+s[5]*i+s[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,s=e.elements,a=1/(s[3]*t+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*n+s[12])*a,this.y=(s[1]*t+s[5]*i+s[9]*n+s[13])*a,this.z=(s[2]*t+s[6]*i+s[10]*n+s[14])*a,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*n-o*i),h=2*(o*t-s*n),u=2*(s*i-a*t);return this.x=t+l*c+a*u-o*h,this.y=i+l*h+o*c-s*u,this.z=n+l*u+s*h-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*n,this.y=s[1]*t+s[5]*i+s[9]*n,this.z=s[2]*t+s[6]*i+s[10]*n,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,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(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=n*l-s*o,this.y=s*a-i*l,this.z=i*o-n*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return RA.copy(this).projectOnVector(e),this.sub(RA)}reflect(e){return this.sub(RA.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(zi(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const RA=new x,bw=new Qe;class en{constructor(e=new x(1/0,1/0,1/0),t=new x(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t+=3)this.expandByPoint(nr.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(nr.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=nr.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(i!==void 0){const s=i.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=s.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,nr):nr.fromBufferAttribute(s,a),nr.applyMatrix4(e.matrixWorld),this.expandByPoint(nr);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Cf.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Cf.copy(i.boundingBox)),Cf.applyMatrix4(e.matrixWorld),this.union(Cf)}const n=e.children;for(let s=0,a=n.length;s<a;s++)this.expandByObject(n[s],t);return this}containsPoint(e){return!(e.x<this.min.x||e.x>this.max.x||e.y<this.min.y||e.y>this.max.y||e.z<this.min.z||e.z>this.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.x<this.min.x||e.min.x>this.max.x||e.max.y<this.min.y||e.min.y>this.max.y||e.max.z<this.min.z||e.min.z>this.max.z)}intersectsSphere(e){return this.clampPoint(e.center,nr),nr.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ru),xf.subVectors(this.max,ru),ac.subVectors(e.a,ru),oc.subVectors(e.b,ru),lc.subVectors(e.c,ru),Ga.subVectors(oc,ac),za.subVectors(lc,oc),Lo.subVectors(ac,lc);let t=[0,-Ga.z,Ga.y,0,-za.z,za.y,0,-Lo.z,Lo.y,Ga.z,0,-Ga.x,za.z,0,-za.x,Lo.z,0,-Lo.x,-Ga.y,Ga.x,0,-za.y,za.x,0,-Lo.y,Lo.x,0];return!BA(t,ac,oc,lc,xf)||(t=[1,0,0,0,1,0,0,0,1],!BA(t,ac,oc,lc,xf))?!1:(Sf.crossVectors(Ga,za),t=[Sf.x,Sf.y,Sf.z],BA(t,ac,oc,lc,xf))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,nr).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(nr).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(sa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),sa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),sa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),sa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),sa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),sa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),sa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),sa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(sa),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const sa=[new x,new x,new x,new x,new x,new x,new x,new x],nr=new x,Cf=new en,ac=new x,oc=new x,lc=new x,Ga=new x,za=new x,Lo=new x,ru=new x,xf=new x,Sf=new x,Oo=new x;function BA(r,e,t,i,n){for(let s=0,a=r.length-3;s<=a;s+=3){Oo.fromArray(r,s);const o=n.x*Math.abs(Oo.x)+n.y*Math.abs(Oo.y)+n.z*Math.abs(Oo.z),l=e.dot(Oo),c=t.dot(Oo),h=i.dot(Oo);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const uD=new en,au=new x,LA=new x;class un{constructor(e=new x,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):uD.setFromPoints(e).getCenter(i);let n=0;for(let s=0,a=e.length;s<a;s++)n=Math.max(n,i.distanceToSquared(e[s]));return this.radius=Math.sqrt(n),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;au.subVectors(e,this.center);const t=au.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(au,n/i),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(LA.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(au.copy(e.center).add(LA)),this.expandByPoint(au.copy(e.center).sub(LA))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const ra=new x,OA=new x,Ef=new x,Va=new x,UA=new x,Mf=new x,FA=new x;class Ha{constructor(e=new x,t=new x(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ra)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=ra.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ra.copy(this.origin).addScaledVector(this.direction,t),ra.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){OA.copy(e).add(t).multiplyScalar(.5),Ef.copy(t).sub(e).normalize(),Va.copy(this.origin).sub(OA);const s=e.distanceTo(t)*.5,a=-this.direction.dot(Ef),o=Va.dot(this.direction),l=-Va.dot(Ef),c=Va.lengthSq(),h=Math.abs(1-a*a);let u,d,p,m;if(h>0)if(u=a*l-o,d=a*o-l,m=s*h,u>=0)if(d>=-m)if(d<=m){const A=1/h;u*=A,d*=A,p=u*(u+a*d+2*o)+d*(a*u+d+2*l)+c}else d=s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;else d=-s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;else d<=-m?(u=Math.max(0,-(-a*s+o)),d=u>0?-s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c):d<=m?(u=0,d=Math.min(Math.max(-s,-l),s),p=d*(d+2*l)+c):(u=Math.max(0,-(a*s+o)),d=u>0?s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c);else d=a>0?-s:s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(OA).addScaledVector(Ef,d),p}intersectSphere(e,t){ra.subVectors(e.center,this.origin);const i=ra.dot(this.direction),n=ra.dot(ra)-i*i,s=e.radius*e.radius;if(n>s)return null;const a=Math.sqrt(s-n),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,s,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,n=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,n=(e.min.x-d.x)*c),h>=0?(s=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(s=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),i>a||s>n||((s>i||isNaN(i))&&(i=s),(a<n||isNaN(n))&&(n=a),u>=0?(o=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),i>l||o>n)||((o>i||i!==i)&&(i=o),(l<n||n!==n)&&(n=l),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,ra)!==null}intersectTriangle(e,t,i,n,s){UA.subVectors(t,e),Mf.subVectors(i,e),FA.crossVectors(UA,Mf);let a=this.direction.dot(FA),o;if(a>0){if(n)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Va.subVectors(this.origin,e);const l=o*this.direction.dot(Mf.crossVectors(Va,Mf));if(l<0)return null;const c=o*this.direction.dot(UA.cross(Va));if(c<0||l+c>a)return null;const h=-o*Va.dot(FA);return h<0?null:this.at(h/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class pe{constructor(e,t,i,n,s,a,o,l,c,h,u,d,p,m,A,g){pe.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,n,s,a,o,l,c,h,u,d,p,m,A,g)}set(e,t,i,n,s,a,o,l,c,h,u,d,p,m,A,g){const y=this.elements;return y[0]=e,y[4]=t,y[8]=i,y[12]=n,y[1]=s,y[5]=a,y[9]=o,y[13]=l,y[2]=c,y[6]=h,y[10]=u,y[14]=d,y[3]=p,y[7]=m,y[11]=A,y[15]=g,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 pe().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,n=1/cc.setFromMatrixColumn(e,0).length(),s=1/cc.setFromMatrixColumn(e,1).length(),a=1/cc.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*s,t[5]=i[5]*s,t[6]=i[6]*s,t[7]=0,t[8]=i[8]*a,t[9]=i[9]*a,t[10]=i[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,s=e.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(s),u=Math.sin(s);if(e.order==="XYZ"){const d=a*h,p=a*u,m=o*h,A=o*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=p+m*c,t[5]=d-A*c,t[9]=-o*l,t[2]=A-d*c,t[6]=m+p*c,t[10]=a*l}else if(e.order==="YXZ"){const d=l*h,p=l*u,m=c*h,A=c*u;t[0]=d+A*o,t[4]=m*o-p,t[8]=a*c,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=p*o-m,t[6]=A+d*o,t[10]=a*l}else if(e.order==="ZXY"){const d=l*h,p=l*u,m=c*h,A=c*u;t[0]=d-A*o,t[4]=-a*u,t[8]=m+p*o,t[1]=p+m*o,t[5]=a*h,t[9]=A-d*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const d=a*h,p=a*u,m=o*h,A=o*u;t[0]=l*h,t[4]=m*c-p,t[8]=d*c+A,t[1]=l*u,t[5]=A*c+d,t[9]=p*c-m,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const d=a*l,p=a*c,m=o*l,A=o*c;t[0]=l*h,t[4]=A-d*u,t[8]=m*u+p,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=p*u+m,t[10]=d-A*u}else if(e.order==="XZY"){const d=a*l,p=a*c,m=o*l,A=o*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+A,t[5]=a*h,t[9]=p*u-m,t[2]=m*u-p,t[6]=o*h,t[10]=A*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(dD,e,fD)}lookAt(e,t,i){const n=this.elements;return Es.subVectors(e,t),Es.lengthSq()===0&&(Es.z=1),Es.normalize(),Qa.crossVectors(i,Es),Qa.lengthSq()===0&&(Math.abs(i.z)===1?Es.x+=1e-4:Es.z+=1e-4,Es.normalize(),Qa.crossVectors(i,Es)),Qa.normalize(),Tf.crossVectors(Es,Qa),n[0]=Qa.x,n[4]=Tf.x,n[8]=Es.x,n[1]=Qa.y,n[5]=Tf.y,n[9]=Es.y,n[2]=Qa.z,n[6]=Tf.z,n[10]=Es.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,s=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],h=i[1],u=i[5],d=i[9],p=i[13],m=i[2],A=i[6],g=i[10],y=i[14],_=i[3],v=i[7],b=i[11],T=i[15],E=n[0],M=n[4],S=n[8],w=n[12],C=n[1],D=n[5],O=n[9],F=n[13],G=n[2],j=n[6],W=n[10],K=n[14],q=n[3],oe=n[7],re=n[11],Ce=n[15];return s[0]=a*E+o*C+l*G+c*q,s[4]=a*M+o*D+l*j+c*oe,s[8]=a*S+o*O+l*W+c*re,s[12]=a*w+o*F+l*K+c*Ce,s[1]=h*E+u*C+d*G+p*q,s[5]=h*M+u*D+d*j+p*oe,s[9]=h*S+u*O+d*W+p*re,s[13]=h*w+u*F+d*K+p*Ce,s[2]=m*E+A*C+g*G+y*q,s[6]=m*M+A*D+g*j+y*oe,s[10]=m*S+A*O+g*W+y*re,s[14]=m*w+A*F+g*K+y*Ce,s[3]=_*E+v*C+b*G+T*q,s[7]=_*M+v*D+b*j+T*oe,s[11]=_*S+v*O+b*W+T*re,s[15]=_*w+v*F+b*K+T*Ce,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],s=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],p=e[14],m=e[3],A=e[7],g=e[11],y=e[15];return m*(+s*l*u-n*c*u-s*o*d+i*c*d+n*o*p-i*l*p)+A*(+t*l*p-t*c*d+s*a*d-n*a*p+n*c*h-s*l*h)+g*(+t*c*u-t*o*p-s*a*u+i*a*p+s*o*h-i*c*h)+y*(-n*o*h-t*l*u+t*o*d+n*a*u-i*a*d+i*l*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],m=e[12],A=e[13],g=e[14],y=e[15],_=u*g*c-A*d*c+A*l*p-o*g*p-u*l*y+o*d*y,v=m*d*c-h*g*c-m*l*p+a*g*p+h*l*y-a*d*y,b=h*A*c-m*u*c+m*o*p-a*A*p-h*o*y+a*u*y,T=m*u*l-h*A*l-m*o*d+a*A*d+h*o*g-a*u*g,E=t*_+i*v+n*b+s*T;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/E;return e[0]=_*M,e[1]=(A*d*s-u*g*s-A*n*p+i*g*p+u*n*y-i*d*y)*M,e[2]=(o*g*s-A*l*s+A*n*c-i*g*c-o*n*y+i*l*y)*M,e[3]=(u*l*s-o*d*s-u*n*c+i*d*c+o*n*p-i*l*p)*M,e[4]=v*M,e[5]=(h*g*s-m*d*s+m*n*p-t*g*p-h*n*y+t*d*y)*M,e[6]=(m*l*s-a*g*s-m*n*c+t*g*c+a*n*y-t*l*y)*M,e[7]=(a*d*s-h*l*s+h*n*c-t*d*c-a*n*p+t*l*p)*M,e[8]=b*M,e[9]=(m*u*s-h*A*s-m*i*p+t*A*p+h*i*y-t*u*y)*M,e[10]=(a*A*s-m*o*s+m*i*c-t*A*c-a*i*y+t*o*y)*M,e[11]=(h*o*s-a*u*s-h*i*c+t*u*c+a*i*p-t*o*p)*M,e[12]=T*M,e[13]=(h*A*n-m*u*n+m*i*d-t*A*d-h*i*g+t*u*g)*M,e[14]=(m*o*n-a*A*n-m*i*l+t*A*l+a*i*g-t*o*g)*M,e[15]=(a*u*n-h*o*n+h*i*l-t*u*l-a*i*d+t*o*d)*M,this}scale(e){const t=this.elements,i=e.x,n=e.y,s=e.z;return t[0]*=i,t[4]*=n,t[8]*=s,t[1]*=i,t[5]*=n,t[9]*=s,t[2]*=i,t[6]*=n,t[10]*=s,t[3]*=i,t[7]*=n,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),s=1-i,a=e.x,o=e.y,l=e.z,c=s*a,h=s*o;return this.set(c*a+i,c*o-n*l,c*l+n*o,0,c*o+n*l,h*o+i,h*l-n*a,0,c*l-n*o,h*l+n*a,s*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,s,a){return this.set(1,i,s,0,e,1,a,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,h=a+a,u=o+o,d=s*c,p=s*h,m=s*u,A=a*h,g=a*u,y=o*u,_=l*c,v=l*h,b=l*u,T=i.x,E=i.y,M=i.z;return n[0]=(1-(A+y))*T,n[1]=(p+b)*T,n[2]=(m-v)*T,n[3]=0,n[4]=(p-b)*E,n[5]=(1-(d+y))*E,n[6]=(g+_)*E,n[7]=0,n[8]=(m+v)*M,n[9]=(g-_)*M,n[10]=(1-(d+A))*M,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;let s=cc.set(n[0],n[1],n[2]).length();const a=cc.set(n[4],n[5],n[6]).length(),o=cc.set(n[8],n[9],n[10]).length();this.determinant()<0&&(s=-s),e.x=n[12],e.y=n[13],e.z=n[14],sr.copy(this);const c=1/s,h=1/a,u=1/o;return sr.elements[0]*=c,sr.elements[1]*=c,sr.elements[2]*=c,sr.elements[4]*=h,sr.elements[5]*=h,sr.elements[6]*=h,sr.elements[8]*=u,sr.elements[9]*=u,sr.elements[10]*=u,t.setFromRotationMatrix(sr),i.x=s,i.y=a,i.z=o,this}makePerspective(e,t,i,n,s,a,o=ia){const l=this.elements,c=2*s/(t-e),h=2*s/(i-n),u=(t+e)/(t-e),d=(i+n)/(i-n);let p,m;if(o===ia)p=-(a+s)/(a-s),m=-2*a*s/(a-s);else if(o===yf)p=-a/(a-s),m=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,i,n,s,a,o=ia){const l=this.elements,c=1/(t-e),h=1/(i-n),u=1/(a-s),d=(t+e)*c,p=(i+n)*h;let m,A;if(o===ia)m=(a+s)*u,A=-2*u;else if(o===yf)m=s*u,A=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=A,l[14]=-m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const cc=new x,sr=new pe,dD=new x(0,0,0),fD=new x(1,1,1),Qa=new x,Tf=new x,Es=new x,ww=new pe,Cw=new Qe;class Tt{constructor(e=0,t=0,i=0,n=Tt.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const n=e.elements,s=n[0],a=n[4],o=n[8],l=n[1],c=n[5],h=n[9],u=n[2],d=n[6],p=n[10];switch(t){case"XYZ":this._y=Math.asin(zi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-zi(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(zi(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-zi(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(zi(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-zi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return ww.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ww,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Cw.setFromEuler(this),this.setFromQuaternion(Cw,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Tt.DEFAULT_ORDER="XYZ";class If{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let pD=0;const xw=new x,hc=new Qe,aa=new pe,Pf=new x,ou=new x,mD=new x,gD=new Qe,Sw=new x(1,0,0),Ew=new x(0,1,0),Mw=new x(0,0,1),Tw={type:"added"},AD={type:"removed"},uc={type:"childadded",child:null},NA={type:"childremoved",child:null};class ft extends wi{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:pD++}),this.uuid=Ss(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ft.DEFAULT_UP.clone();const e=new x,t=new Tt,i=new Qe,n=new x(1,1,1);function s(){i.setFromEuler(t,!1)}function a(){t.setFromQuaternion(i,void 0,!1)}t._onChange(s),i._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new pe},normalMatrix:{value:new mt}}),this.matrix=new pe,this.matrixWorld=new pe,this.matrixAutoUpdate=ft.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ft.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new If,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(e,t,i,n,s,a){this.dispatchEvent({type:"beforeRender",renderer:e,scene:t,camera:i,geometry:n,material:s,group:a})}onAfterRender(e,t,i,n,s,a){this.dispatchEvent({type:"afterRender",renderer:e,scene:t,camera:i,geometry:n,material:s,group:a})}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return hc.setFromAxisAngle(e,t),this.quaternion.multiply(hc),this}rotateOnWorldAxis(e,t){return hc.setFromAxisAngle(e,t),this.quaternion.premultiply(hc),this}rotateX(e){return this.rotateOnAxis(Sw,e)}rotateY(e){return this.rotateOnAxis(Ew,e)}rotateZ(e){return this.rotateOnAxis(Mw,e)}translateOnAxis(e,t){return xw.copy(e).applyQuaternion(this.quaternion),this.position.add(xw.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Sw,e)}translateY(e){return this.translateOnAxis(Ew,e)}translateZ(e){return this.translateOnAxis(Mw,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(aa.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?Pf.copy(e):Pf.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),ou.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?aa.lookAt(ou,Pf,this.up):aa.lookAt(Pf,ou,this.up),this.quaternion.setFromRotationMatrix(aa),n&&(aa.extractRotation(n.matrixWorld),hc.setFromRotationMatrix(aa),this.quaternion.premultiply(hc.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Tw),uc.child=e,this.dispatchEvent(uc),uc.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(AD),NA.child=e,this.dispatchEvent(NA),NA.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),aa.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),aa.multiply(e.parent.matrixWorld)),e.applyMatrix4(aa),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Tw),uc.child=e,this.dispatchEvent(uc),uc.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,n=this.children.length;i<n;i++){const a=this.children[i].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let s=0,a=n.length;s<a;s++)n[s].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ou,e,mD),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ou,gD,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++){const s=t[i];(s.matrixWorldAutoUpdate===!0||e===!0)&&s.updateMatrixWorld(e)}}updateWorldMatrix(e,t){const i=this.parent;if(e===!0&&i!==null&&i.matrixWorldAutoUpdate===!0&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),t===!0){const n=this.children;for(let s=0,a=n.length;s<a;s++){const o=n[s];o.matrixWorldAutoUpdate===!0&&o.updateWorldMatrix(!1,!0)}}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{},extras:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.visibility=this._visibility,n.active=this._active,n.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),n.maxGeometryCount=this._maxGeometryCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.geometryCount=this._geometryCount,n.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(n.boundingSphere={center:n.boundingSphere.center.toArray(),radius:n.boundingSphere.radius}),this.boundingBox!==null&&(n.boundingBox={min:n.boundingBox.min.toArray(),max:n.boundingBox.max.toArray()}));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const u=l[c];s(e.shapes,u)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(s(e.materials,this.material[l]));n.material=o}else n.material=s(e.materials,this.material);if(this.children.length>0){n.children=[];for(let o=0;o<this.children.length;o++)n.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let o=0;o<this.animations.length;o++){const l=this.animations[o];n.animations.push(s(e.animations,l))}}if(t){const o=a(e.geometries),l=a(e.materials),c=a(e.textures),h=a(e.images),u=a(e.shapes),d=a(e.skeletons),p=a(e.animations),m=a(e.nodes);o.length>0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),p.length>0&&(i.animations=p),m.length>0&&(i.nodes=m)}return i.object=n,i;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData={};for(const[i,n]of Object.entries(e.userData))this.userData[i]=!n||n&&(n.isTexture||n.isObject3D)?n:JSON.parse(JSON.stringify(n));if(t===!0)for(let i=0;i<e.children.length;i++){const n=e.children[i];this.add(n.clone())}return this}}ft.DEFAULT_UP=new x(0,1,0),ft.DEFAULT_MATRIX_AUTO_UPDATE=!0,ft.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const rr=new x,oa=new x,kA=new x,la=new x,dc=new x,fc=new x,Iw=new x,GA=new x,zA=new x,VA=new x;class ns{constructor(e=new x,t=new x,i=new x){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),rr.subVectors(e,t),n.cross(rr);const s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(e,t,i,n,s){rr.subVectors(n,t),oa.subVectors(i,t),kA.subVectors(e,t);const a=rr.dot(rr),o=rr.dot(oa),l=rr.dot(kA),c=oa.dot(oa),h=oa.dot(kA),u=a*c-o*o;if(u===0)return s.set(0,0,0),null;const d=1/u,p=(c*l-o*h)*d,m=(a*h-o*l)*d;return s.set(1-p-m,m,p)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,la)===null?!1:la.x>=0&&la.y>=0&&la.x+la.y<=1}static getInterpolation(e,t,i,n,s,a,o,l){return this.getBarycoord(e,t,i,n,la)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,la.x),l.addScaledVector(a,la.y),l.addScaledVector(o,la.z),l)}static isFrontFacing(e,t,i,n){return rr.subVectors(i,t),oa.subVectors(e,t),rr.cross(oa).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return rr.subVectors(this.c,this.b),oa.subVectors(this.a,this.b),rr.cross(oa).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ns.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ns.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,s){return ns.getInterpolation(e,this.a,this.b,this.c,t,i,n,s)}containsPoint(e){return ns.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ns.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,s=this.c;let a,o;dc.subVectors(n,i),fc.subVectors(s,i),GA.subVectors(e,i);const l=dc.dot(GA),c=fc.dot(GA);if(l<=0&&c<=0)return t.copy(i);zA.subVectors(e,n);const h=dc.dot(zA),u=fc.dot(zA);if(h>=0&&u<=h)return t.copy(n);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(i).addScaledVector(dc,a);VA.subVectors(e,s);const p=dc.dot(VA),m=fc.dot(VA);if(m>=0&&p<=m)return t.copy(s);const A=p*c-l*m;if(A<=0&&c>=0&&m<=0)return o=c/(c-m),t.copy(i).addScaledVector(fc,o);const g=h*m-p*u;if(g<=0&&u-h>=0&&p-m>=0)return Iw.subVectors(s,n),o=(u-h)/(u-h+(p-m)),t.copy(n).addScaledVector(Iw,o);const y=1/(g+A+d);return a=A*y,o=d*y,t.copy(i).addScaledVector(dc,a).addScaledVector(fc,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Pw={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},ja={h:0,s:0,l:0},Df={h:0,s:0,l:0};function HA(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*6*(2/3-t):r}class se{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=vt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Xt.toWorkingColorSpace(this,t),this}setRGB(e,t,i,n=Xt.workingColorSpace){return this.r=e,this.g=t,this.b=i,Xt.toWorkingColorSpace(this,n),this}setHSL(e,t,i,n=Xt.workingColorSpace){if(e=MA(e,1),t=zi(t,0,1),i=zi(i,0,1),t===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+t):i+t-i*t,a=2*i-s;this.r=HA(a,s,e+1/3),this.g=HA(a,s,e),this.b=HA(a,s,e-1/3)}return Xt.toWorkingColorSpace(this,n),this}setStyle(e,t=vt){function i(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=n[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=vt){const i=Pw[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=sc(e.r),this.g=sc(e.g),this.b=sc(e.b),this}copyLinearToSRGB(e){return this.r=IA(e.r),this.g=IA(e.g),this.b=IA(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=vt){return Xt.fromWorkingColorSpace(Vn.copy(this),e),Math.round(zi(Vn.r*255,0,255))*65536+Math.round(zi(Vn.g*255,0,255))*256+Math.round(zi(Vn.b*255,0,255))}getHexString(e=vt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Xt.workingColorSpace){Xt.fromWorkingColorSpace(Vn.copy(this),t);const i=Vn.r,n=Vn.g,s=Vn.b,a=Math.max(i,n,s),o=Math.min(i,n,s);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const u=a-o;switch(c=h<=.5?u/(a+o):u/(2-a-o),a){case i:l=(n-s)/u+(n<s?6:0);break;case n:l=(s-i)/u+2;break;case s:l=(i-n)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=Xt.workingColorSpace){return Xt.fromWorkingColorSpace(Vn.copy(this),t),e.r=Vn.r,e.g=Vn.g,e.b=Vn.b,e}getStyle(e=vt){Xt.fromWorkingColorSpace(Vn.copy(this),e);const t=Vn.r,i=Vn.g,n=Vn.b;return e!==vt?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(e,t,i){return this.getHSL(ja),this.setHSL(ja.h+e,ja.s+t,ja.l+i)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(ja),e.getHSL(Df);const i=iu(ja.h,Df.h,t),n=iu(ja.s,Df.s,t),s=iu(ja.l,Df.l,t);return this.setHSL(i,n,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,n=this.b,s=e.elements;return this.r=s[0]*t+s[3]*i+s[6]*n,this.g=s[1]*t+s[4]*i+s[7]*n,this.b=s[2]*t+s[5]*i+s[8]*n,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Vn=new se;se.NAMES=Pw;let yD=0;class tn extends wi{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:yD++}),this.uuid=Ss(),this.name="",this.type="Material",this.blending=xr,this.side=fs,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Hl,this.blendDst=Ql,this.blendEquation=Sr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new se(0,0,0),this.blendAlpha=0,this.depthFunc=ql,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=SA,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ta,this.stencilZFail=ta,this.stencilZPass=ta,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onAfterRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];n!==void 0&&(n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):Array.isArray(i)&&n&&typeof n.fromArray=="function"?n.fromArray(i):this[t]=i)}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.6001,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==xr&&(i.blending=this.blending),this.side!==fs&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Hl&&(i.blendSrc=this.blendSrc),this.blendDst!==Ql&&(i.blendDst=this.blendDst),this.blendEquation!==Sr&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==ql&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==SA&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ta&&(i.stencilFail=this.stencilFail),this.stencilZFail!==ta&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==ta&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(s){const a=[];for(const o in s){const l=s[o];delete l.metadata,a.push(l)}return a}if(t){const s=n(e.textures),a=n(e.images);s.length>0&&(i.textures=s),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let s=0;s!==n;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=Dw({},e.userData),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}function Dw(r,e){if(!e)return r;for(const t of Object.keys(e)){if(t.startsWith("__")||typeof r[t]=="function"||typeof e[t]=="function")continue;const i=e[t],n=!i||i.isTexture||i.isObject3D||i.isMaterial||i.isBufferGeometry||i.userDataSkipClone;!n&&typeof e[t].clone=="function"?r[t]=e[t].clone():!n&&(typeof e[t]=="object"||Array.isArray(e[t]))?r[t]=Dw(Array.isArray(e[t])?[]:{},e[t]):r[t]=e[t]}return r}class ss extends tn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new se(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Tt,this.combine=Xl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const ca=vD();function vD(){const r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),i=new Uint32Array(512),n=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,n[l]=24,n[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,n[l]=-c-1,n[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,n[l]=13,n[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,n[l]=24,n[l|256]=24):(i[l]=31744,i[l|256]=64512,n[l]=13,n[l|256]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,s[l]=c|h}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:a,offsetTable:o}}function ms(r){Math.abs(r)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),r=zi(r,-65504,65504),ca.floatView[0]=r;const e=ca.uint32View[0],t=e>>23&511;return ca.baseTable[t]+((e&8388607)>>ca.shiftTable[t])}function lu(r){const e=r>>10;return ca.uint32View[0]=ca.mantissaTable[ca.offsetTable[e]+(r&1023)]+ca.exponentTable[e],ca.floatView[0]}const Hn={toHalfFloat:ms,fromHalfFloat:lu},dn=new x,Rf=new $;class Xe{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=Af,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=zt,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return su("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,s=this.itemSize;n<s;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)Rf.fromBufferAttribute(this,t),Rf.applyMatrix3(e),this.setXY(t,Rf.x,Rf.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix3(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix4(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyNormalMatrix(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.transformDirection(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=is(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=wt(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=is(t,this.array)),t}setX(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=is(t,this.array)),t}setY(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=is(t,this.array)),t}setZ(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=is(t,this.array)),t}setW(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array),n=wt(n,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,s){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array),n=wt(n,this.array),s=wt(s,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Af&&(e.usage=this.usage),e}}class _D extends Xe{constructor(e,t,i){super(new Int8Array(e),t,i)}}class bD extends Xe{constructor(e,t,i){super(new Uint8Array(e),t,i)}}class wD extends Xe{constructor(e,t,i){super(new Uint8ClampedArray(e),t,i)}}class CD extends Xe{constructor(e,t,i){super(new Int16Array(e),t,i)}}class Bf extends Xe{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class xD extends Xe{constructor(e,t,i){super(new Int32Array(e),t,i)}}class QA extends Xe{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class SD extends Xe{constructor(e,t,i){super(new Uint16Array(e),t,i),this.isFloat16BufferAttribute=!0}getX(e){let t=lu(this.array[e*this.itemSize]);return this.normalized&&(t=is(t,this.array)),t}setX(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize]=ms(t),this}getY(e){let t=lu(this.array[e*this.itemSize+1]);return this.normalized&&(t=is(t,this.array)),t}setY(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+1]=ms(t),this}getZ(e){let t=lu(this.array[e*this.itemSize+2]);return this.normalized&&(t=is(t,this.array)),t}setZ(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+2]=ms(t),this}getW(e){let t=lu(this.array[e*this.itemSize+3]);return this.normalized&&(t=is(t,this.array)),t}setW(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+3]=ms(t),this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array)),this.array[e+0]=ms(t),this.array[e+1]=ms(i),this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array),n=wt(n,this.array)),this.array[e+0]=ms(t),this.array[e+1]=ms(i),this.array[e+2]=ms(n),this}setXYZW(e,t,i,n,s){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array),n=wt(n,this.array),s=wt(s,this.array)),this.array[e+0]=ms(t),this.array[e+1]=ms(i),this.array[e+2]=ms(n),this.array[e+3]=ms(s),this}}class Me extends Xe{constructor(e,t,i){super(new Float32Array(e),t,i)}}let ED=0;const zs=new pe,jA=new ft,Uo=new x,Ms=new en,cu=new en,En=new x;class $e extends wi{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:ED++}),this.uuid=Ss(),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(e){return Array.isArray(e)?this.index=new(mw(e)?QA:Bf)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new mt().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return zs.makeRotationFromQuaternion(e),this.applyMatrix4(zs),this}rotateX(e){return zs.makeRotationX(e),this.applyMatrix4(zs),this}rotateY(e){return zs.makeRotationY(e),this.applyMatrix4(zs),this}rotateZ(e){return zs.makeRotationZ(e),this.applyMatrix4(zs),this}translate(e,t,i){return zs.makeTranslation(e,t,i),this.applyMatrix4(zs),this}scale(e,t,i){return zs.makeScale(e,t,i),this.applyMatrix4(zs),this}lookAt(e){return jA.lookAt(e),jA.updateMatrix(),this.applyMatrix4(jA.matrix),this}center(e=void 0){return this.computeBoundingBox(),this.boundingBox.getCenter(Uo).negate(),this.translate(Uo.x,Uo.y,Uo.z),e&&e.copy(Uo),this}setFromPoints(e){const t=[];for(let i=0,n=e.length;i<n;i++){const s=e[i];t.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new Me(t,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new en);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new x(-1/0,-1/0,-1/0),new x(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i<n;i++){const s=t[i];Ms.setFromBufferAttribute(s),this.morphTargetsRelative?(En.addVectors(this.boundingBox.min,Ms.min),this.boundingBox.expandByPoint(En),En.addVectors(this.boundingBox.max,Ms.max),this.boundingBox.expandByPoint(En)):(this.boundingBox.expandByPoint(Ms.min),this.boundingBox.expandByPoint(Ms.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new x,1/0);return}if(e){const i=this.boundingSphere.center;if(Ms.setFromBufferAttribute(e),t)for(let s=0,a=t.length;s<a;s++){const o=t[s];cu.setFromBufferAttribute(o),this.morphTargetsRelative?(En.addVectors(Ms.min,cu.min),Ms.expandByPoint(En),En.addVectors(Ms.max,cu.max),Ms.expandByPoint(En)):(Ms.expandByPoint(cu.min),Ms.expandByPoint(cu.max))}Ms.getCenter(i);let n=0;for(let s=0,a=e.count;s<a;s++)En.fromBufferAttribute(e,s),n=Math.max(n,i.distanceToSquared(En));if(t)for(let s=0,a=t.length;s<a;s++){const o=t[s],l=this.morphTargetsRelative;for(let c=0,h=o.count;c<h;c++)En.fromBufferAttribute(o,c),l&&(Uo.fromBufferAttribute(e,c),En.add(Uo)),n=Math.max(n,i.distanceToSquared(En))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=t.position,n=t.normal,s=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Xe(new Float32Array(4*i.count),4));const a=this.getAttribute("tangent"),o=[],l=[];for(let S=0;S<i.count;S++)o[S]=new x,l[S]=new x;const c=new x,h=new x,u=new x,d=new $,p=new $,m=new $,A=new x,g=new x;function y(S,w,C){c.fromBufferAttribute(i,S),h.fromBufferAttribute(i,w),u.fromBufferAttribute(i,C),d.fromBufferAttribute(s,S),p.fromBufferAttribute(s,w),m.fromBufferAttribute(s,C),h.sub(c),u.sub(c),p.sub(d),m.sub(d);const D=1/(p.x*m.y-m.x*p.y);isFinite(D)&&(A.copy(h).multiplyScalar(m.y).addScaledVector(u,-p.y).multiplyScalar(D),g.copy(u).multiplyScalar(p.x).addScaledVector(h,-m.x).multiplyScalar(D),o[S].add(A),o[w].add(A),o[C].add(A),l[S].add(g),l[w].add(g),l[C].add(g))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let S=0,w=_.length;S<w;++S){const C=_[S],D=C.start,O=C.count;for(let F=D,G=D+O;F<G;F+=3)y(e.getX(F+0),e.getX(F+1),e.getX(F+2))}const v=new x,b=new x,T=new x,E=new x;function M(S){T.fromBufferAttribute(n,S),E.copy(T);const w=o[S];v.copy(w),v.sub(T.multiplyScalar(T.dot(w))).normalize(),b.crossVectors(E,w);const D=b.dot(l[S])<0?-1:1;a.setXYZW(S,v.x,v.y,v.z,D)}for(let S=0,w=_.length;S<w;++S){const C=_[S],D=C.start,O=C.count;for(let F=D,G=D+O;F<G;F+=3)M(e.getX(F+0)),M(e.getX(F+1)),M(e.getX(F+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new Xe(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let d=0,p=i.count;d<p;d++)i.setXYZ(d,0,0,0);const n=new x,s=new x,a=new x,o=new x,l=new x,c=new x,h=new x,u=new x;if(e)for(let d=0,p=e.count;d<p;d+=3){const m=e.getX(d+0),A=e.getX(d+1),g=e.getX(d+2);n.fromBufferAttribute(t,m),s.fromBufferAttribute(t,A),a.fromBufferAttribute(t,g),h.subVectors(a,s),u.subVectors(n,s),h.cross(u),o.fromBufferAttribute(i,m),l.fromBufferAttribute(i,A),c.fromBufferAttribute(i,g),o.add(h),l.add(h),c.add(h),i.setXYZ(m,o.x,o.y,o.z),i.setXYZ(A,l.x,l.y,l.z),i.setXYZ(g,c.x,c.y,c.z)}else for(let d=0,p=t.count;d<p;d+=3)n.fromBufferAttribute(t,d+0),s.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),h.subVectors(a,s),u.subVectors(n,s),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)En.fromBufferAttribute(e,t),En.normalize(),e.setXYZ(t,En.x,En.y,En.z)}toNonIndexed(){function e(o,l){const c=o.array,h=o.itemSize,u=o.normalized,d=new c.constructor(l.length*h);let p=0,m=0;for(let A=0,g=l.length;A<g;A++){o.isInterleavedBufferAttribute?p=l[A]*o.data.stride+o.offset:p=l[A]*h;for(let y=0;y<h;y++)d[m++]=c[p++]}return new Xe(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new $e,i=this.index.array,n=this.attributes;for(const o in n){const l=n[o],c=e(l,i);t.setAttribute(o,c)}const s=this.morphAttributes;for(const o in s){const l=[],c=s[o];for(let h=0,u=c.length;h<u;h++){const d=c[h],p=e(d,i);l.push(p)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,l=a.length;o<l;o++){const c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u];h.push(p.toJSON(e.data))}h.length>0&&(n[l]=h,s=!0)}s&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone(t));const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const s=e.morphAttributes;for(const c in s){const h=[],u=s[c];for(let d=0,p=u.length;d<p;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let c=0,h=a.length;c<h;c++){const u=a[c];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Rw=new pe,Fo=new Ha,Lf=new un,Bw=new x,pc=new x,mc=new x,gc=new x,WA=new x,Of=new x,Uf=new $,Ff=new $,Nf=new $,Lw=new x,Ow=new x,Uw=new x,kf=new x,Gf=new x;class ye extends ft{constructor(e=new $e,t=new ss){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.isMesh?(e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this):this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=n.length;s<a;s++){const o=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}getVertexPosition(e,t){const i=this.geometry,n=i.attributes.position,s=i.morphAttributes.position,a=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const o=this.morphTargetInfluences;if(s&&o){Of.set(0,0,0);for(let l=0,c=s.length;l<c;l++){const h=o[l],u=s[l];h!==0&&(WA.fromBufferAttribute(u,e),a?Of.addScaledVector(WA,h):Of.addScaledVector(WA.sub(t),h))}t.add(Of)}return t}raycast(e,t){const i=this.geometry,n=this.material,s=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),Lf.copy(i.boundingSphere),Lf.applyMatrix4(s),Fo.copy(e.ray).recast(e.near),!(Lf.containsPoint(Fo.origin)===!1&&(Fo.intersectSphere(Lf,Bw)===null||Fo.origin.distanceToSquared(Bw)>(e.far-e.near)**2))&&(Rw.copy(s).invert(),Fo.copy(e.ray).applyMatrix4(Rw),!(i.boundingBox!==null&&Fo.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Fo)))}_computeIntersections(e,t,i){let n;const s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,p=s.drawRange;if(o!==null)if(Array.isArray(a))for(let m=0,A=d.length;m<A;m++){const g=d[m],y=a[g.materialIndex],_=Math.max(g.start,p.start),v=Math.min(o.count,Math.min(g.start+g.count,p.start+p.count));for(let b=_,T=v;b<T;b+=3){const E=o.getX(b),M=o.getX(b+1),S=o.getX(b+2);n=zf(this,y,e,i,c,h,u,E,M,S),n&&(n.faceIndex=Math.floor(b/3),n.face.materialIndex=g.materialIndex,t.push(n))}}else{const m=Math.max(0,p.start),A=Math.min(o.count,p.start+p.count);for(let g=m,y=A;g<y;g+=3){const _=o.getX(g),v=o.getX(g+1),b=o.getX(g+2);n=zf(this,a,e,i,c,h,u,_,v,b),n&&(n.faceIndex=Math.floor(g/3),t.push(n))}}else if(l!==void 0)if(Array.isArray(a))for(let m=0,A=d.length;m<A;m++){const g=d[m],y=a[g.materialIndex],_=Math.max(g.start,p.start),v=Math.min(l.count,Math.min(g.start+g.count,p.start+p.count));for(let b=_,T=v;b<T;b+=3){const E=b,M=b+1,S=b+2;n=zf(this,y,e,i,c,h,u,E,M,S),n&&(n.faceIndex=Math.floor(b/3),n.face.materialIndex=g.materialIndex,t.push(n))}}else{const m=Math.max(0,p.start),A=Math.min(l.count,p.start+p.count);for(let g=m,y=A;g<y;g+=3){const _=g,v=g+1,b=g+2;n=zf(this,a,e,i,c,h,u,_,v,b),n&&(n.faceIndex=Math.floor(g/3),t.push(n))}}}}function MD(r,e,t,i,n,s,a,o){let l;if(e.side===Rn?l=i.intersectTriangle(a,s,n,!0,o):l=i.intersectTriangle(n,s,a,e.side===fs,o),l===null)return null;Gf.copy(o),Gf.applyMatrix4(r.matrixWorld);const c=t.ray.origin.distanceTo(Gf);return c<t.near||c>t.far?null:{distance:c,point:Gf.clone(),object:r}}function zf(r,e,t,i,n,s,a,o,l,c){r.getVertexPosition(o,pc),r.getVertexPosition(l,mc),r.getVertexPosition(c,gc);const h=MD(r,e,t,i,pc,mc,gc,kf);if(h){n&&(Uf.fromBufferAttribute(n,o),Ff.fromBufferAttribute(n,l),Nf.fromBufferAttribute(n,c),h.uv=ns.getInterpolation(kf,pc,mc,gc,Uf,Ff,Nf,new $)),s&&(Uf.fromBufferAttribute(s,o),Ff.fromBufferAttribute(s,l),Nf.fromBufferAttribute(s,c),h.uv1=ns.getInterpolation(kf,pc,mc,gc,Uf,Ff,Nf,new $)),a&&(Lw.fromBufferAttribute(a,o),Ow.fromBufferAttribute(a,l),Uw.fromBufferAttribute(a,c),h.normal=ns.getInterpolation(kf,pc,mc,gc,Lw,Ow,Uw,new x),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const u={a:o,b:l,c,normal:new x,materialIndex:0};ns.getNormal(pc,mc,gc,u.normal),h.face=u}return h}class mi extends $e{constructor(e=1,t=1,i=1,n=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:s,depthSegments:a};const o=this;n=Math.floor(n),s=Math.floor(s),a=Math.floor(a);const l=[],c=[],h=[],u=[];let d=0,p=0;m("z","y","x",-1,-1,i,t,e,a,s,0),m("z","y","x",1,-1,i,t,-e,a,s,1),m("x","z","y",1,1,e,i,t,n,a,2),m("x","z","y",1,-1,e,i,-t,n,a,3),m("x","y","z",1,-1,e,t,i,n,s,4),m("x","y","z",-1,-1,e,t,-i,n,s,5),this.setIndex(l),this.setAttribute("position",new Me(c,3)),this.setAttribute("normal",new Me(h,3)),this.setAttribute("uv",new Me(u,2));function m(A,g,y,_,v,b,T,E,M,S,w){const C=b/M,D=T/S,O=b/2,F=T/2,G=E/2,j=M+1,W=S+1;let K=0,q=0;const oe=new x;for(let re=0;re<W;re++){const Ce=re*D-F;for(let Ie=0;Ie<j;Ie++){const Ue=Ie*C-O;oe[A]=Ue*_,oe[g]=Ce*v,oe[y]=G,c.push(oe.x,oe.y,oe.z),oe[A]=0,oe[g]=0,oe[y]=E>0?1:-1,h.push(oe.x,oe.y,oe.z),u.push(Ie/M),u.push(1-re/S),K+=1}}for(let re=0;re<S;re++)for(let Ce=0;Ce<M;Ce++){const Ie=d+Ce+j*re,Ue=d+Ce+j*(re+1),te=d+(Ce+1)+j*(re+1),ce=d+(Ce+1)+j*re;l.push(Ie,Ue,ce),l.push(Ue,te,ce),q+=6}o.addGroup(p,q,w),p+=q,d+=K}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new mi(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function No(r){const e={};for(const t in r){e[t]={};for(const i in r[t]){const n=r[t][i];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=n.clone():Array.isArray(n)?e[t][i]=n.slice():e[t][i]=n}}return e}function rs(r){const e={};for(let t=0;t<r.length;t++){const i=No(r[t]);for(const n in i)e[n]=i[n]}return e}function TD(r){const e=[];for(let t=0;t<r.length;t++)e.push(r[t].clone());return e}function Fw(r){const e=r.getRenderTarget();return e===null?r.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Xt.workingColorSpace}const ko={clone:No,merge:rs};var ID=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,PD=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;class nn extends tn{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=ID,this.fragmentShader=PD,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=No(e.uniforms),this.uniformsGroups=TD(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const n in this.uniforms){const a=this.uniforms[n].value;a&&a.isTexture?t.uniforms[n]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[n]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[n]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[n]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[n]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[n]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[n]={type:"m4",value:a.toArray()}:t.uniforms[n]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class Ac extends ft{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new pe,this.projectionMatrix=new pe,this.projectionMatrixInverse=new pe,this.coordinateSystem=ia}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Wa=new x,Nw=new $,kw=new $;class Vi extends Ac{constructor(e=50,t=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=ic*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Bo*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ic*2*Math.atan(Math.tan(Bo*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Wa.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Wa.x,Wa.y).multiplyScalar(-e/Wa.z),Wa.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Wa.x,Wa.y).multiplyScalar(-e/Wa.z)}getViewSize(e,t){return this.getViewBounds(e,Nw,kw),t.subVectors(kw,Nw)}setViewOffset(e,t,i,n,s,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Bo*.5*this.fov)/this.zoom,i=2*t,n=this.aspect*i,s=-.5*n;const a=this.view;if(this.view!==null&&this.view.enabled){const l=a.fullWidth,c=a.fullHeight;s+=a.offsetX*n/l,t-=a.offsetY*i/c,n*=a.width/l,i*=a.height/c}const o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+n,t,t-i,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const yc=-90,vc=1;class Gw extends ft{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new Vi(yc,vc,e,t);n.layers=this.layers,this.add(n);const s=new Vi(yc,vc,e,t);s.layers=this.layers,this.add(s);const a=new Vi(yc,vc,e,t);a.layers=this.layers,this.add(a);const o=new Vi(yc,vc,e,t);o.layers=this.layers,this.add(o);const l=new Vi(yc,vc,e,t);l.layers=this.layers,this.add(l);const c=new Vi(yc,vc,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,n,s,a,o,l]=t;for(const c of t)this.remove(c);if(e===ia)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===yf)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,a,o,l,c,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;const A=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,n),e.render(t,s),e.setRenderTarget(i,1,n),e.render(t,a),e.setRenderTarget(i,2,n),e.render(t,o),e.setRenderTarget(i,3,n),e.render(t,l),e.setRenderTarget(i,4,n),e.render(t,c),i.texture.generateMipmaps=A,e.setRenderTarget(i,5,n),e.render(t,h),e.setRenderTarget(u,d,p),e.xr.enabled=m,i.texture.needsPMREMUpdate=!0}}class _c extends Rt{constructor(e,t,i,n,s,a,o,l,c,h){e=e!==void 0?e:[],t=t!==void 0?t:Kr,super(e,t,i,n,s,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class qA extends ps{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},n=[i,i,i,i,i,i];this.texture=new _c(n,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:st}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:`

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`,fragmentShader:`

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`},n=new mi(5,5,5),s=new nn({name:"CubemapFromEquirect",uniforms:No(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:Rn,blending:gn});s.uniforms.tEquirect.value=t;const a=new ye(n,s),o=t.minFilter;return t.minFilter===Ln&&(t.minFilter=st),new Gw(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,i,n){const s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,n);e.setRenderTarget(s)}}const XA=new x,DD=new x,RD=new mt;class Ts{constructor(e=new x(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,i,n){return this.normal.set(e,t,i),this.constant=n,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const n=XA.subVectors(i,t).cross(DD.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(n,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const i=e.delta(XA),n=this.normal.dot(i);if(n===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/n;return s<0||s>1?null:t.copy(e.start).addScaledVector(i,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||RD.getNormalMatrix(e),n=this.coplanarPoint(XA).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Go=new un,Vf=new x;class hu{constructor(e=new Ts,t=new Ts,i=new Ts,n=new Ts,s=new Ts,a=new Ts){this.planes=[e,t,i,n,s,a]}set(e,t,i,n,s,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(n),o[4].copy(s),o[5].copy(a),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=ia){const i=this.planes,n=e.elements,s=n[0],a=n[1],o=n[2],l=n[3],c=n[4],h=n[5],u=n[6],d=n[7],p=n[8],m=n[9],A=n[10],g=n[11],y=n[12],_=n[13],v=n[14],b=n[15];if(i[0].setComponents(l-s,d-c,g-p,b-y).normalize(),i[1].setComponents(l+s,d+c,g+p,b+y).normalize(),i[2].setComponents(l+a,d+h,g+m,b+_).normalize(),i[3].setComponents(l-a,d-h,g-m,b-_).normalize(),i[4].setComponents(l-o,d-u,g-A,b-v).normalize(),t===ia)i[5].setComponents(l+o,d+u,g+A,b+v).normalize();else if(t===yf)i[5].setComponents(o,u,A,v).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Go.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Go.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Go)}intersectsSprite(e){return Go.center.set(0,0,0),Go.radius=.7071067811865476,Go.applyMatrix4(e.matrixWorld),this.intersectsSphere(Go)}intersectsSphere(e){const t=this.planes,i=e.center,n=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)<n)return!1;return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const n=t[i];if(Vf.x=n.normal.x>0?e.max.x:e.min.x,Vf.y=n.normal.y>0?e.max.y:e.min.y,Vf.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(Vf)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function zw(){let r=null,e=!1,t=null,i=null;function n(s,a){t(s,a),i=r.requestAnimationFrame(n)}return{start:function(){e!==!0&&t!==null&&(i=r.requestAnimationFrame(n),e=!0)},stop:function(){r.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){r=s}}}function BD(r){const e=new WeakMap;function t(o,l){const c=o.array,h=o.usage,u=c.byteLength,d=r.createBuffer();r.bindBuffer(l,d),r.bufferData(l,c,h),o.onUploadCallback();let p;if(c instanceof Float32Array)p=r.FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?p=r.HALF_FLOAT:p=r.UNSIGNED_SHORT;else if(c instanceof Int16Array)p=r.SHORT;else if(c instanceof Uint32Array)p=r.UNSIGNED_INT;else if(c instanceof Int32Array)p=r.INT;else if(c instanceof Int8Array)p=r.BYTE;else if(c instanceof Uint8Array)p=r.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)p=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:d,type:p,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:u}}function i(o,l,c){const h=l.array,u=l._updateRange,d=l.updateRanges;if(r.bindBuffer(c,o),u.count===-1&&d.length===0&&r.bufferSubData(c,0,h),d.length!==0){for(let p=0,m=d.length;p<m;p++){const A=d[p];r.bufferSubData(c,A.start*h.BYTES_PER_ELEMENT,h,A.start,A.count)}l.clearUpdateRanges()}u.count!==-1&&(r.bufferSubData(c,u.offset*h.BYTES_PER_ELEMENT,h,u.offset,u.count),u.count=-1),l.onUploadCallback()}function n(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function s(o){o.isInterleavedBufferAttribute&&(o=o.data);const l=e.get(o);l&&(r.deleteBuffer(l.buffer),e.delete(o))}function a(o,l){if(o.isGLBufferAttribute){const h=e.get(o);(!h||h.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}o.isInterleavedBufferAttribute&&(o=o.data);const c=e.get(o);if(c===void 0)e.set(o,t(o,l));else if(c.version<o.version){if(c.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(c.buffer,o,l),c.version=o.version}}return{get:n,remove:s,update:a}}class Er extends $e{constructor(e=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:n};const s=e/2,a=t/2,o=Math.floor(i),l=Math.floor(n),c=o+1,h=l+1,u=e/o,d=t/l,p=[],m=[],A=[],g=[];for(let y=0;y<h;y++){const _=y*d-a;for(let v=0;v<c;v++){const b=v*u-s;m.push(b,-_,0),A.push(0,0,1),g.push(v/o),g.push(1-y/l)}}for(let y=0;y<l;y++)for(let _=0;_<o;_++){const v=_+c*y,b=_+c*(y+1),T=_+1+c*(y+1),E=_+1+c*y;p.push(v,b,E),p.push(b,T,E)}this.setIndex(p),this.setAttribute("position",new Me(m,3)),this.setAttribute("normal",new Me(A,3)),this.setAttribute("uv",new Me(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Er(e.width,e.height,e.widthSegments,e.heightSegments)}}var LD=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,OD=`#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`,UD=`#ifdef USE_ALPHAMAP
	#if defined(INVERSE_ALPHAMAP) && INVERSE_ALPHAMAP >= 1
	diffuseColor.a *= 1.0-texture2D( alphaMap, vAlphaMapUv ).g;
	#else
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
	#endif
#endif`,FD=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,ND=`#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`,kD=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,GD=`#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`,zD=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,VD=`#ifdef USE_BATCHING
	attribute float batchId;
	uniform highp sampler2D batchingTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`,HD=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( batchId );
#endif`,QD=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,jD=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,WD=`float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`,qD=`#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`,XD=`#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`,YD=`#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`,$D=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,KD=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,JD=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,ZD=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,eR=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,tR=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
	varying vec3 vColor;
#endif`,iR=`#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif`,nR=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
float luminance( const in vec3 rgb ) {
	const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );
	return dot( weights, rgb );
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,sR=`#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`,rR=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`,aR=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,oR=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,lR=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,cR=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,hR="gl_FragColor = linearToOutputTexel( gl_FragColor );",uR=`
const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
	vec3( 0.8224621, 0.177538, 0.0 ),
	vec3( 0.0331941, 0.9668058, 0.0 ),
	vec3( 0.0170827, 0.0723974, 0.9105199 )
);
const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
	vec3( 1.2249401, - 0.2249404, 0.0 ),
	vec3( - 0.0420569, 1.0420571, 0.0 ),
	vec3( - 0.0196376, - 0.0786361, 1.0982735 )
);
vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
	return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
}
vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
	return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
}
vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return 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 );
}
vec4 LinearToLinear( in vec4 value ) {
	return value;
}
vec4 LinearTosRGB( in vec4 value ) {
	return sRGBTransferOETF( value );
}
vec4 sRGBToLinear( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 RGBM16ToLinear( in vec4 value ) {
	return vec4( value.rgb * value.a * 16.0, 1.0 );
}
vec4 LinearToRGBM16( in vec4 value ) {
	float maxRGB = max( value.r, max( value.g, value.b ) );
	float M = clamp( maxRGB / 16.0, 0.0, 1.0 );
	M = ceil( M * 255.0 ) / 255.0;
	return vec4( value.rgb / ( M * 16.0 ), M );
}`,dR=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`,fR=`#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
#endif`,pR=`#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`,mR=`#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`,gR=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`,AR=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,yR=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,vR=`#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,_R=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,bR=`#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`,wR=`#ifdef USE_LIGHTMAP
	vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
	vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
	reflectedLight.indirectDiffuse += lightMapIrradiance;
#endif`,CR=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,xR=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,SR=`varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void 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 ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void 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 ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`,ER=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	#if defined ( LEGACY_LIGHTS )
		if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {
			return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );
		}
		return 1.0;
	#else
		float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
		if ( cutoffDistance > 0.0 ) {
			distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
		}
		return distanceFalloff;
	#endif
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`,MR=`#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
		#if defined( FIX_ENV_DIRECTION )
			vec3 worldNormal = normal;
		#else
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#endif
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			#if !defined( FIX_ENV_DIRECTION )
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			#endif
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`,TR=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,IR=`varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void 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 ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void 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 ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`,PR=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,DR=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void 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 ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void 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 ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`,RR=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,BR=`struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#if defined( USE_ANISOTROPY ) || defined( USE_ANISOTROPY_BRDF )
	float 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 ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void 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 ) {
#else
void 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 ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void 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 ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void 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 ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void 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 ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void 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) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,LR=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,OR=`#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`,UR=`#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,FR=`#if defined( USE_LOGDEPTHBUF )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,NR=`#if defined( USE_LOGDEPTHBUF )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,kR=`#ifdef USE_LOGDEPTHBUF
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,GR=`#ifdef USE_LOGDEPTHBUF
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,zR=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = 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 );
	
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,VR=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,HR=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,QR=`#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,jR=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,WR=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,qR=`#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[MORPHTARGETS_COUNT];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`,XR=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`,YR=`#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	#ifdef MORPHTARGETS_TEXTURE
		for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
			if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
		}
	#else
		objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];
		objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];
		objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];
		objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];
	#endif
#endif`,$R=`#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
	#endif
	#ifdef MORPHTARGETS_TEXTURE
		#ifndef USE_INSTANCING_MORPH
			uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
		#endif
		uniform sampler2DArray morphTargetsTexture;
		uniform ivec2 morphTargetsTextureSize;
		vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
			int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
			int y = texelIndex / morphTargetsTextureSize.x;
			int x = texelIndex - y * morphTargetsTextureSize.x;
			ivec3 morphUV = ivec3( x, y, morphTargetIndex );
			return texelFetch( morphTargetsTexture, morphUV, 0 );
		}
	#else
		#ifndef USE_MORPHNORMALS
			uniform float morphTargetInfluences[ 8 ];
		#else
			uniform float morphTargetInfluences[ 4 ];
		#endif
	#endif
#endif`,KR=`#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	#ifdef MORPHTARGETS_TEXTURE
		for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
			if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
		}
	#else
		transformed += morphTarget0 * morphTargetInfluences[ 0 ];
		transformed += morphTarget1 * morphTargetInfluences[ 1 ];
		transformed += morphTarget2 * morphTargetInfluences[ 2 ];
		transformed += morphTarget3 * morphTargetInfluences[ 3 ];
		#ifndef USE_MORPHNORMALS
			transformed += morphTarget4 * morphTargetInfluences[ 4 ];
			transformed += morphTarget5 * morphTargetInfluences[ 5 ];
			transformed += morphTarget6 * morphTargetInfluences[ 6 ];
			transformed += morphTarget7 * morphTargetInfluences[ 7 ];
		#endif
	#endif
#endif`,JR=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`,ZR=`#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,eB=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,tB=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,iB=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,nB=`#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`,sB=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,rB=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,aB=`#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`,oB=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,lB=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
diffuseColor.a = min(max(diffuseColor.a, 0.), 1.);
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,cB=`vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;
const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );
const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );
const float ShiftRight8 = 1. / 256.;
vec4 packDepthToRGBA( const in float v ) {
	vec4 r = vec4( fract( v * PackFactors ), v );
	r.yzw -= r.xyz * ShiftRight8;	return r * PackUpscale;
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors );
}
vec2 packDepthToRG( in highp float v ) {
	return packDepthToRGBA( v ).yx;
}
float unpackRGToDepth( const in highp vec2 v ) {
	return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );
}
vec4 pack2HalfToRGBA( vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`,hB=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,uB=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,dB=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,fB=`#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`,pB=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,mB=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,gB=`#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		float hard_shadow = step( compare , distribution.x );
		if (hard_shadow != 1.0 ) {
			float distance = compare - distribution.x ;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return shadow;
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return shadow;
	}
#endif`,AB=`#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`,yB=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`,vB=`float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`,_B=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,bB=`#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`,wB=`#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,CB=`#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`,xB=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,SB=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,EB=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,MB=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 OptimizedCineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	float startCompression = 0.8 - 0.04;
	float desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min(color.r, min(color.g, color.b));
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max(color.r, max(color.g, color.b));
	if (peak < startCompression) return color;
	float d = 1. - startCompression;
	float newPeak = 1. - d * d / (peak + d - startCompression);
	color *= newPeak / peak;
	float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);
	return mix(color, newPeak * vec3(1, 1, 1), g);
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,TB=`#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,IB=`#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	#ifndef WebGL2Context
	#define textureLod texture2DLodEXT
	#define textureSize(s, lod) vec2(1024./pow(2.,float(lod)),1024./pow(2.,float(lod)))
	#define isinf(x) (x > 1e20 || x < -1e20)
	#endif
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		if(roughness == 0.0) return transmissionSamplerMapTexelToLinear( texture2D( transmissionSamplerMap, fragCoord.xy ) );
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return transmissionSamplerMapTexelToLinear( textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ) );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) || attenuationDistance == 0.0) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
		vec3 refractedRayExit = position + transmissionRay;
		vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
		vec2 refractionCoords = ndcPos.xy / ndcPos.w;
		refractionCoords += 1.0;
		refractionCoords /= 2.0;
		vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
		vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`,PB=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,DB=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,RB=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`,BB=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;const ot={alphahash_fragment:LD,alphahash_pars_fragment:OD,alphamap_fragment:UD,alphamap_pars_fragment:FD,alphatest_fragment:ND,alphatest_pars_fragment:kD,aomap_fragment:GD,aomap_pars_fragment:zD,batching_pars_vertex:VD,batching_vertex:HD,begin_vertex:QD,beginnormal_vertex:jD,bsdfs:WD,iridescence_fragment:qD,bumpmap_pars_fragment:XD,clipping_planes_fragment:YD,clipping_planes_pars_fragment:$D,clipping_planes_pars_vertex:KD,clipping_planes_vertex:JD,color_fragment:ZD,color_pars_fragment:eR,color_pars_vertex:tR,color_vertex:iR,common:nR,cube_uv_reflection_fragment:sR,defaultnormal_vertex:rR,displacementmap_pars_vertex:aR,displacementmap_vertex:oR,emissivemap_fragment:lR,emissivemap_pars_fragment:cR,colorspace_fragment:hR,colorspace_pars_fragment:uR,envmap_fragment:dR,envmap_common_pars_fragment:fR,envmap_pars_fragment:pR,envmap_pars_vertex:mR,envmap_physical_pars_fragment:MR,envmap_vertex:gR,fog_vertex:AR,fog_pars_vertex:yR,fog_fragment:vR,fog_pars_fragment:_R,gradientmap_pars_fragment:bR,lightmap_fragment:wR,lightmap_pars_fragment:CR,lights_lambert_fragment:xR,lights_lambert_pars_fragment:SR,lights_pars_begin:ER,lights_toon_fragment:TR,lights_toon_pars_fragment:IR,lights_phong_fragment:PR,lights_phong_pars_fragment:DR,lights_physical_fragment:RR,lights_physical_pars_fragment:BR,lights_fragment_begin:LR,lights_fragment_maps:OR,lights_fragment_end:UR,logdepthbuf_fragment:FR,logdepthbuf_pars_fragment:NR,logdepthbuf_pars_vertex:kR,logdepthbuf_vertex:GR,map_fragment:zR,map_pars_fragment:VR,map_particle_fragment:HR,map_particle_pars_fragment:QR,metalnessmap_fragment:jR,metalnessmap_pars_fragment:WR,morphinstance_vertex:qR,morphcolor_vertex:XR,morphnormal_vertex:YR,morphtarget_pars_vertex:$R,morphtarget_vertex:KR,normal_fragment_begin:JR,normal_fragment_maps:ZR,normal_pars_fragment:eB,normal_pars_vertex:tB,normal_vertex:iB,normalmap_pars_fragment:nB,clearcoat_normal_fragment_begin:sB,clearcoat_normal_fragment_maps:rB,clearcoat_pars_fragment:aB,iridescence_pars_fragment:oB,opaque_fragment:lB,packing:cB,premultiplied_alpha_fragment:hB,project_vertex:uB,dithering_fragment:dB,dithering_pars_fragment:fB,roughnessmap_fragment:pB,roughnessmap_pars_fragment:mB,shadowmap_pars_fragment:gB,shadowmap_pars_vertex:AB,shadowmap_vertex:yB,shadowmask_pars_fragment:vB,skinbase_vertex:_B,skinning_pars_vertex:bB,skinning_vertex:wB,skinnormal_vertex:CB,specularmap_fragment:xB,specularmap_pars_fragment:SB,tonemapping_fragment:EB,tonemapping_pars_fragment:MB,transmission_fragment:TB,transmission_pars_fragment:IB,uv_pars_fragment:PB,uv_pars_vertex:DB,uv_vertex:RB,worldpos_vertex:BB,background_vert:`#ifdef HAS_TEXTURE
varying vec2 vUv;
uniform mat3 uvTransform;
uniform bool flipX;
uniform bool flipY;
#endif
void main() {
#ifdef HAS_TEXTURE
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
    vUv = flipX ? vec2( 1.0 - vUv.x, vUv.y ) : vUv;
    vUv = flipY ? vec2( vUv.x, 1.0 - vUv.y ) : vUv;
#endif
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,background_frag:`#ifdef HAS_TEXTURE
uniform sampler2D t2D;
varying vec2 vUv;
#endif
uniform float backgroundIntensity;
uniform vec3 backgroundColor;
void main() {
#ifdef HAS_TEXTURE
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = 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 );
	#endif
#else
	vec4 texColor = vec4( 1.0 );
#endif
	texColor.rgb *= backgroundColor * backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,backgroundCube_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,cube_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,cube_frag:`uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,depth_vert:`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`,depth_frag:`#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#endif
}`,distanceRGBA_vert:`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`,distanceRGBA_frag:`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`,equirect_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`,equirect_frag:`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,linedashed_vert:`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,linedashed_frag:`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,meshbasic_vert:`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`,meshbasic_frag:`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshlambert_vert:`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,meshlambert_frag:`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshmatcap_vert:`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`,meshmatcap_frag:`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshnormal_vert:`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`,meshnormal_frag:`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`,meshphong_vert:`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,meshphong_frag:`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshphysical_vert:`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`,meshphysical_frag:`#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,meshtoon_vert:`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,meshtoon_frag:`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,points_vert:`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`,points_frag:`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,shadow_vert:`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,shadow_frag:`uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`,sprite_vert:`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
	vec2 scale;
	scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
	scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,sprite_frag:`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`},Re={common:{diffuse:{value:new se(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new mt},alphaMap:{value:null},alphaMapTransform:{value:new mt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new mt}},envmap:{envMap:{value:null},envMapRotation:{value:new mt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new mt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new mt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new mt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new mt},normalScale:{value:new $(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new mt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new mt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new mt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new mt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new se(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 se(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new mt},alphaTest:{value:0},uvTransform:{value:new mt}},sprite:{diffuse:{value:new se(16777215)},opacity:{value:1},center:{value:new $(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new mt},alphaMap:{value:null},alphaMapTransform:{value:new mt},alphaTest:{value:0}}},Di={basic:{uniforms:rs([Re.common,Re.specularmap,Re.envmap,Re.aomap,Re.lightmap,Re.fog]),vertexShader:ot.meshbasic_vert,fragmentShader:ot.meshbasic_frag},lambert:{uniforms:rs([Re.common,Re.specularmap,Re.envmap,Re.aomap,Re.lightmap,Re.emissivemap,Re.bumpmap,Re.normalmap,Re.displacementmap,Re.fog,Re.lights,{emissive:{value:new se(0)}}]),vertexShader:ot.meshlambert_vert,fragmentShader:ot.meshlambert_frag},phong:{uniforms:rs([Re.common,Re.specularmap,Re.envmap,Re.aomap,Re.lightmap,Re.emissivemap,Re.bumpmap,Re.normalmap,Re.displacementmap,Re.fog,Re.lights,{emissive:{value:new se(0)},specular:{value:new se(1118481)},shininess:{value:30}}]),vertexShader:ot.meshphong_vert,fragmentShader:ot.meshphong_frag},standard:{uniforms:rs([Re.common,Re.envmap,Re.aomap,Re.lightmap,Re.emissivemap,Re.bumpmap,Re.normalmap,Re.displacementmap,Re.roughnessmap,Re.metalnessmap,Re.fog,Re.lights,{emissive:{value:new se(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ot.meshphysical_vert,fragmentShader:ot.meshphysical_frag},toon:{uniforms:rs([Re.common,Re.aomap,Re.lightmap,Re.emissivemap,Re.bumpmap,Re.normalmap,Re.displacementmap,Re.gradientmap,Re.fog,Re.lights,{emissive:{value:new se(0)}}]),vertexShader:ot.meshtoon_vert,fragmentShader:ot.meshtoon_frag},matcap:{uniforms:rs([Re.common,Re.bumpmap,Re.normalmap,Re.displacementmap,Re.fog,{matcap:{value:null}}]),vertexShader:ot.meshmatcap_vert,fragmentShader:ot.meshmatcap_frag},points:{uniforms:rs([Re.points,Re.fog]),vertexShader:ot.points_vert,fragmentShader:ot.points_frag},dashed:{uniforms:rs([Re.common,Re.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ot.linedashed_vert,fragmentShader:ot.linedashed_frag},depth:{uniforms:rs([Re.common,Re.displacementmap]),vertexShader:ot.depth_vert,fragmentShader:ot.depth_frag},normal:{uniforms:rs([Re.common,Re.bumpmap,Re.normalmap,Re.displacementmap,{opacity:{value:1}}]),vertexShader:ot.meshnormal_vert,fragmentShader:ot.meshnormal_frag},sprite:{uniforms:rs([Re.sprite,Re.fog]),vertexShader:ot.sprite_vert,fragmentShader:ot.sprite_frag},background:{uniforms:{uvTransform:{value:new mt},t2D:{value:null},backgroundIntensity:{value:1},backgroundColor:{value:new se(16777215)},flipX:{value:!1},flipY:{value:!1}},vertexShader:ot.background_vert,fragmentShader:ot.background_frag},backgroundCube:{uniforms:{envMap:{value:null},envMapRotation:{value:0},envMapIntensity:{value:1},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new mt}},vertexShader:ot.backgroundCube_vert,fragmentShader:ot.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ot.cube_vert,fragmentShader:ot.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ot.equirect_vert,fragmentShader:ot.equirect_frag},distanceRGBA:{uniforms:rs([Re.common,Re.displacementmap,{referencePosition:{value:new x},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ot.distanceRGBA_vert,fragmentShader:ot.distanceRGBA_frag},shadow:{uniforms:rs([Re.lights,Re.fog,{color:{value:new se(0)},opacity:{value:1}}]),vertexShader:ot.shadow_vert,fragmentShader:ot.shadow_frag}};Di.physical={uniforms:rs([Di.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new mt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new mt},clearcoatNormalScale:{value:new $(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new mt},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new mt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new mt},sheen:{value:0},sheenColor:{value:new se(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new mt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new mt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new mt},transmissionSamplerSize:{value:new $},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new mt},attenuationDistance:{value:0},attenuationColor:{value:new se(0)},specularColor:{value:new se(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new mt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new mt},anisotropyVector:{value:new $},anisotropyMap:{value:null},anisotropyMapTransform:{value:new mt}}]),vertexShader:ot.meshphysical_vert,fragmentShader:ot.meshphysical_frag};const Hf={r:0,b:0,g:0},gs=new Tt,Vw=new pe,LB=new mt;function OB(r,e,t,i,n,s,a){const o=new se(0);let l=s===!0?0:1,c,h,u=null,d=0,p=null;function m(g,y){let _=!1,v=y.isScene===!0?y.background:null;const b=y.isScene&&y.backgroundColor!==void 0?y.backgroundColor:null;v==="environment"&&(v=y.environment);const T=v&&v===y.environment;v&&v.isTexture&&(v=(y.backgroundBlurriness>0?t:e).get(v)),v===null?A(o,l):v&&v.isColor&&(A(v,1),_=!0);const E=r.xr.getEnvironmentBlendMode();if(E==="additive"?i.buffers.color.setClear(0,0,0,1,a):E==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,a),(r.autoClear||_)&&r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil),v&&(v.isCubeTexture||v.mapping===Yl))h===void 0&&(h=new ye(new mi(1,1,1),new nn({name:"BackgroundCubeMaterial",uniforms:No(Di.backgroundCube.uniforms),vertexShader:Di.backgroundCube.vertexShader,fragmentShader:Di.backgroundCube.fragmentShader,side:Rn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(M,S,w){this.matrixWorld.copyPosition(w.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),gs.copy(y.backgroundRotation),gs.x*=-1,gs.y*=-1,gs.z*=-1,v.isCubeTexture&&v.isRenderTargetTexture===!1&&(gs.y*=-1,gs.z*=-1),h.material.uniforms.envMap.value=v,h.material.uniforms.flipEnvMap.value=v.isCubeTexture&&v.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=y.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(Vw.makeRotationFromEuler(gs)),h.material.toneMapped=Xt.getTransfer(v.colorSpace)!==bi,T&&(h.material.uniforms.backgroundIntensity.value*=y.environmentIntensity,gs.copy(y.environmentRotation),gs.x*=-1,gs.y*=-1,gs.z*=-1,v.isCubeTexture&&v.isRenderTargetTexture===!1&&(gs.y*=-1,gs.z*=-1),h.material.uniforms.backgroundRotation.value.premultiply(LB.setFromMatrix4(Vw.makeRotationFromEuler(gs)))),(u!==v||d!==v.version||p!==r.toneMapping)&&(h.material.needsUpdate=!0,u=v,d=v.version,p=r.toneMapping),h.layers.enableAll(),g.unshift(h,h.geometry,h.material,0,0,null);else if(v&&v.isTexture||!v&&b){c===void 0&&(c=new ye(new Er(2,2),new nn({name:"BackgroundMaterial",uniforms:No(Di.background.uniforms),vertexShader:Di.background.vertexShader,fragmentShader:Di.background.fragmentShader,side:fs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.backgroundColor.value.set(b||16777215),c.material.uniforms.t2D.value=v,c.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,v?(c.material.toneMapped=Xt.getTransfer(v.colorSpace)!==bi,c.material.uniforms.flipX.value=v.userData.flipX||!1,c.material.uniforms.flipY.value=v.userData.flipY||!1,v.matrixAutoUpdate===!0&&v.updateMatrix(),c.material.uniforms.uvTransform.value.copy(v.matrix),c.material.defines.HAS_TEXTURE="1"):c.material.defines.HAS_TEXTURE&&delete c.material.defines.HAS_TEXTURE;const M=v?v.version:-1;(u!==v||d!==M||p!==r.toneMapping)&&(c.material.needsUpdate=!0,u=v,d=M,p=r.toneMapping),c.layers.enableAll(),g.unshift(c,c.geometry,c.material,0,0,null)}}function A(g,y){g.getRGB(Hf,Fw(r)),i.buffers.color.setClear(Hf.r,Hf.g,Hf.b,y,a)}return{getClearColor:function(){return o},setClearColor:function(g,y=1){o.set(g),l=y,A(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(g){l=g,A(o,l)},getPlaneMesh:function(){return c},getBoxMesh:function(){return h},getBoxMesh2:function(){return h===void 0&&(h=new ye(new mi(1,1,1),new nn({name:"BackgroundCubeMaterial",uniforms:No(Di.backgroundCube.uniforms),vertexShader:Di.backgroundCube.vertexShader,fragmentShader:Di.backgroundCube.fragmentShader,side:Rn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(g,y,_){this.matrixWorld.copyPosition(_.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),h},render:m}}function UB(r,e){const t=r.getParameter(r.MAX_VERTEX_ATTRIBS),i={},n=d(null);let s=n,a=!1;function o(C,D,O,F,G){let j=!1;const W=u(F,O,D);s!==W&&(s=W,c(s.object)),j=p(C,F,O,G),j&&m(C,F,O,G),G!==null&&e.update(G,r.ELEMENT_ARRAY_BUFFER),(j||a)&&(a=!1,b(C,D,O,F),G!==null&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.get(G).buffer))}function l(){return r.createVertexArray()}function c(C){return r.bindVertexArray(C)}function h(C){return r.deleteVertexArray(C)}function u(C,D,O){const F=O.wireframe===!0;let G=i[C.id];G===void 0&&(G={},i[C.id]=G);let j=G[D.id];j===void 0&&(j={},G[D.id]=j);let W=j[F];return W===void 0&&(W=d(l()),j[F]=W),W}function d(C){const D=[],O=[],F=[];for(let G=0;G<t;G++)D[G]=0,O[G]=0,F[G]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:D,enabledAttributes:O,attributeDivisors:F,object:C,attributes:{},index:null}}function p(C,D,O,F){const G=s.attributes,j=D.attributes;let W=0;const K=O.getAttributes();for(const q in K)if(K[q].location>=0){const re=G[q];let Ce=j[q];if(Ce===void 0&&(q==="instanceMatrix"&&C.instanceMatrix&&(Ce=C.instanceMatrix),q==="instanceColor"&&C.instanceColor&&(Ce=C.instanceColor)),re===void 0||re.attribute!==Ce||Ce&&re.data!==Ce.data)return!0;W++}return s.attributesNum!==W||s.index!==F}function m(C,D,O,F){const G={},j=D.attributes;let W=0;const K=O.getAttributes();for(const q in K)if(K[q].location>=0){let re=j[q];re===void 0&&(q==="instanceMatrix"&&C.instanceMatrix&&(re=C.instanceMatrix),q==="instanceColor"&&C.instanceColor&&(re=C.instanceColor));const Ce={};Ce.attribute=re,re&&re.data&&(Ce.data=re.data),G[q]=Ce,W++}s.attributes=G,s.attributesNum=W,s.index=F}function A(){const C=s.newAttributes;for(let D=0,O=C.length;D<O;D++)C[D]=0}function g(C){y(C,0)}function y(C,D){const O=s.newAttributes,F=s.enabledAttributes,G=s.attributeDivisors;O[C]=1,F[C]===0&&(r.enableVertexAttribArray(C),F[C]=1),G[C]!==D&&(r.vertexAttribDivisor(C,D),G[C]=D)}function _(){const C=s.newAttributes,D=s.enabledAttributes;for(let O=0,F=D.length;O<F;O++)D[O]!==C[O]&&(r.disableVertexAttribArray(O),D[O]=0)}function v(C,D,O,F,G,j,W){W===!0?r.vertexAttribIPointer(C,D,O,G,j):r.vertexAttribPointer(C,D,O,F,G,j)}function b(C,D,O,F){A();const G=F.attributes,j=O.getAttributes(),W=D.defaultAttributeValues;for(const K in j){const q=j[K];if(q.location>=0){let oe=G[K];if(oe===void 0&&(K==="instanceMatrix"&&C.instanceMatrix&&(oe=C.instanceMatrix),K==="instanceColor"&&C.instanceColor&&(oe=C.instanceColor)),oe!==void 0){const re=oe.normalized,Ce=oe.itemSize,Ie=e.get(oe);if(Ie===void 0)continue;const Ue=Ie.buffer,te=Ie.type,ce=Ie.bytesPerElement,me=te===r.INT||te===r.UNSIGNED_INT||oe.gpuType===lA;if(oe.isInterleavedBufferAttribute){const we=oe.data,je=we.stride,ht=oe.offset;if(we.isInstancedInterleavedBuffer){for(let Ze=0;Ze<q.locationSize;Ze++)y(q.location+Ze,we.meshPerAttribute);C.isInstancedMesh!==!0&&F._maxInstanceCount===void 0&&(F._maxInstanceCount=we.meshPerAttribute*we.count)}else for(let Ze=0;Ze<q.locationSize;Ze++)g(q.location+Ze);r.bindBuffer(r.ARRAY_BUFFER,Ue);for(let Ze=0;Ze<q.locationSize;Ze++)v(q.location+Ze,Ce/q.locationSize,te,re,je*ce,(ht+Ce/q.locationSize*Ze)*ce,me)}else{if(oe.isInstancedBufferAttribute){for(let we=0;we<q.locationSize;we++)y(q.location+we,oe.meshPerAttribute);C.isInstancedMesh!==!0&&F._maxInstanceCount===void 0&&(F._maxInstanceCount=oe.meshPerAttribute*oe.count)}else for(let we=0;we<q.locationSize;we++)g(q.location+we);r.bindBuffer(r.ARRAY_BUFFER,Ue);for(let we=0;we<q.locationSize;we++)v(q.location+we,Ce/q.locationSize,te,re,Ce*ce,Ce/q.locationSize*we*ce,me)}}else if(W!==void 0){const re=W[K];if(re!==void 0)switch(re.length){case 2:r.vertexAttrib2fv(q.location,re);break;case 3:r.vertexAttrib3fv(q.location,re);break;case 4:r.vertexAttrib4fv(q.location,re);break;default:r.vertexAttrib1fv(q.location,re)}}}}_()}function T(){S();for(const C in i){const D=i[C];for(const O in D){const F=D[O];for(const G in F)h(F[G].object),delete F[G];delete D[O]}delete i[C]}}function E(C){if(i[C.id]===void 0)return;const D=i[C.id];for(const O in D){const F=D[O];for(const G in F)h(F[G].object),delete F[G];delete D[O]}delete i[C.id]}function M(C){for(const D in i){const O=i[D];if(O[C.id]===void 0)continue;const F=O[C.id];for(const G in F)h(F[G].object),delete F[G];delete O[C.id]}}function S(){w(),a=!0,s!==n&&(s=n,c(s.object))}function w(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:o,reset:S,resetDefaultState:w,dispose:T,releaseStatesOfGeometry:E,releaseStatesOfProgram:M,initAttributes:A,enableAttribute:g,disableUnusedAttributes:_}}function FB(r,e,t){let i;function n(l){i=l}function s(l,c){r.drawArrays(i,l,c),t.update(c,i,1)}function a(l,c,h){h!==0&&(r.drawArraysInstanced(i,l,c,h),t.update(c,i,h))}function o(l,c,h){if(h===0)return;const u=e.get("WEBGL_multi_draw");if(u===null)for(let d=0;d<h;d++)this.render(l[d],c[d]);else{u.multiDrawArraysWEBGL(i,l,0,c,0,h);let d=0;for(let p=0;p<h;p++)d+=c[p];t.update(d,i,1)}}this.setMode=n,this.render=s,this.renderInstances=a,this.renderMultiDraw=o}function NB(r,e,t){let i;function n(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){const v=e.get("EXT_texture_filter_anisotropic");i=r.getParameter(v.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function s(v){if(v==="highp"){if(r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";v="mediump"}return v==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=t.precision!==void 0?t.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=t.logarithmicDepthBuffer===!0,c=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),h=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),u=r.getParameter(r.MAX_TEXTURE_SIZE),d=r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),p=r.getParameter(r.MAX_VERTEX_ATTRIBS),m=r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),A=r.getParameter(r.MAX_VARYING_VECTORS),g=r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),y=h>0,_=r.getParameter(r.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:n,getMaxPrecision:s,precision:a,logarithmicDepthBuffer:l,maxTextures:c,maxVertexTextures:h,maxTextureSize:u,maxCubemapSize:d,maxAttributes:p,maxVertexUniforms:m,maxVaryings:A,maxFragmentUniforms:g,vertexTextures:y,maxSamples:_}}function kB(r){const e=this;let t=null,i=0,n=!1,s=!1;const a=new Ts,o=new mt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const p=u.length!==0||d||i!==0||n;return n=d,i=u.length,p},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,p){const m=u.clippingPlanes,A=u.clipIntersection,g=u.clipShadows,y=r.get(u);if(!n||m===null||m.length===0||s&&!g)s?h(null):c();else{const _=s?0:i,v=_*4;let b=y.clippingState||null;l.value=b,b=h(m,d,v,p);for(let T=0;T!==v;++T)b[T]=t[T];y.clippingState=b,this.numIntersection=A?this.numPlanes:0,this.numPlanes+=_}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(u,d,p,m){const A=u!==null?u.length:0;let g=null;if(A!==0){if(g=l.value,m!==!0||g===null){const y=p+A*4,_=d.matrixWorldInverse;o.getNormalMatrix(_),(g===null||g.length<y)&&(g=new Float32Array(y));for(let v=0,b=p;v!==A;++v,b+=4)a.copy(u[v]).applyMatrix4(_,o),a.normal.toArray(g,b),g[b+3]=a.constant}l.value=g,l.needsUpdate=!0}return e.numPlanes=A,e.numIntersection=0,g}}function GB(r){let e=new WeakMap;function t(a,o){return o===Jr?a.mapping=Kr:o===lf&&(a.mapping=Io),a}function i(a){if(a&&a.isTexture){const o=a.mapping;if(o===Jr||o===lf)if(e.has(a)){const l=e.get(a).texture;return t(l,a.mapping)}else{const l=a.image;if(l&&l.height>0){const c=new qA(l.height);return c.fromEquirectangularTexture(r,a),e.set(a,c),a.addEventListener("dispose",n),t(c.texture,a.mapping)}else return null}}return a}function n(a){const o=a.target;o.removeEventListener("dispose",n);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function s(){e=new WeakMap}return{get:i,dispose:s}}class Mr extends Ac{constructor(e=-1,t=1,i=1,n=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=n,this.near=s,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,i,n,s,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let s=i-e,a=i+e,o=n+t,l=n-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,a=s+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const bc=4,Hw=[.125,.215,.35,.446,.526,.582],zo=20,YA=new Mr,Qw=new se;let $A=null,KA=0,JA=0,ZA=!1;const Vo=(1+Math.sqrt(5))/2,wc=1/Vo,jw=[new x(1,1,1),new x(-1,1,1),new x(1,1,-1),new x(-1,1,-1),new x(0,Vo,wc),new x(0,Vo,-wc),new x(wc,0,Vo),new x(-wc,0,Vo),new x(Vo,wc,0),new x(-Vo,wc,0)];class ey{constructor(e){this._renderer=e,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(e,t=0,i=.1,n=100){$A=this._renderer.getRenderTarget(),KA=this._renderer.getActiveCubeFace(),JA=this._renderer.getActiveMipmapLevel(),ZA=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,i,n,s),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Xw(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=qw(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget($A,KA,JA),this._renderer.xr.enabled=ZA,e.scissorTest=!1,Qf(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===Kr||e.mapping===Io?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),$A=this._renderer.getRenderTarget(),KA=this._renderer.getActiveCubeFace(),JA=this._renderer.getActiveMipmapLevel(),ZA=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const i=t||this._allocateTargets();return this._textureToCubeUV(e,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,i={magFilter:st,minFilter:st,generateMipmaps:!1,type:$t,format:Kt,colorSpace:Dt,depthBuffer:!1},n=Ww(e,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ww(e,t,i);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=zB(s)),this._blurMaterial=VB(s,e,t)}return n}_compileMaterial(e){const t=new ye(this._lodPlanes[0],e);this._renderer.compile(t,YA)}_sceneToCubeUV(e,t,i,n){const o=new Vi(90,1,t,i),l=[1,-1,1,1,1,1],c=[1,1,1,-1,-1,-1],h=this._renderer,u=h.autoClear,d=h.toneMapping;h.getClearColor(Qw),h.toneMapping=$r,h.autoClear=!1;const p=new ss({name:"PMREM.Background",side:Rn,depthWrite:!1,depthTest:!1}),m=new ye(new mi,p);let A=!1;const g=e.background;g?g.isColor&&(p.color.copy(g),e.background=null,A=!0):(p.color.copy(Qw),A=!0);for(let y=0;y<6;y++){const _=y%3;_===0?(o.up.set(0,l[y],0),o.lookAt(c[y],0,0)):_===1?(o.up.set(0,0,l[y]),o.lookAt(0,c[y],0)):(o.up.set(0,l[y],0),o.lookAt(0,0,c[y]));const v=this._cubeSize;Qf(n,_*v,y>2?v:0,v,v),h.setRenderTarget(n),A&&h.render(m,o),h.render(e,o)}m.geometry.dispose(),m.material.dispose(),h.toneMapping=d,h.autoClear=u,e.background=g}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===Kr||e.mapping===Io;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=Xw()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=qw());const s=n?this._cubemapMaterial:this._equirectMaterial,a=new ye(this._lodPlanes[0],s),o=s.uniforms;o.envMap.value=e;const l=this._cubeSize;Qf(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,YA)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;for(let n=1;n<this._lodPlanes.length;n++){const s=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),a=jw[(n-1)%jw.length];this._blur(e,n-1,n,s,a)}t.autoClear=i}_blur(e,t,i,n,s){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,n,"latitudinal",s),this._halfBlur(a,e,i,i,n,"longitudinal",s)}_halfBlur(e,t,i,n,s,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=new ye(this._lodPlanes[n],c),d=c.uniforms,p=this._sizeLods[i]-1,m=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*zo-1),A=s/m,g=isFinite(s)?1+Math.floor(h*A):zo;g>zo&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${zo}`);const y=[];let _=0;for(let M=0;M<zo;++M){const S=M/A,w=Math.exp(-S*S/2);y.push(w),M===0?_+=w:M<g&&(_+=2*w)}for(let M=0;M<y.length;M++)y[M]=y[M]/_;d.envMap.value=e.texture,d.samples.value=g,d.weights.value=y,d.latitudinal.value=a==="latitudinal",o&&(d.poleAxis.value=o);const{_lodMax:v}=this;d.dTheta.value=m,d.mipInt.value=v-i;const b=this._sizeLods[n],T=3*b*(n>v-bc?n-v+bc:0),E=4*(this._cubeSize-b);Qf(t,T,E,3*b,2*b),l.setRenderTarget(t),l.render(u,YA)}}function zB(r){const e=[],t=[],i=[];let n=r;const s=r-bc+1+Hw.length;for(let a=0;a<s;a++){const o=Math.pow(2,n);t.push(o);let l=1/o;a>r-bc?l=Hw[a-r+bc-1]:a===0&&(l=0),i.push(l);const c=1/(o-2),h=-c,u=1+c,d=[h,h,u,h,u,u,h,h,u,u,h,u],p=6,m=6,A=3,g=2,y=1,_=new Float32Array(A*m*p),v=new Float32Array(g*m*p),b=new Float32Array(y*m*p);for(let E=0;E<p;E++){const M=E%3*2/3-1,S=E>2?0:-1,w=[M,S,0,M+2/3,S,0,M+2/3,S+1,0,M,S,0,M+2/3,S+1,0,M,S+1,0];_.set(w,A*m*E),v.set(d,g*m*E);const C=[E,E,E,E,E,E];b.set(C,y*m*E)}const T=new $e;T.setAttribute("position",new Xe(_,A)),T.setAttribute("uv",new Xe(v,g)),T.setAttribute("faceIndex",new Xe(b,y)),e.push(T),n>bc&&n--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function Ww(r,e,t){const i=new ps(r,e,t);return i.texture.mapping=Yl,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Qf(r,e,t,i,n){r.viewport.set(e,t,i,n),r.scissor.set(e,t,i,n)}function VB(r,e,t){const i=new Float32Array(zo),n=new x(0,1,0);return new nn({name:"SphericalGaussianBlur",defines:{n:zo,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:ty(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`,blending:gn,depthTest:!1,depthWrite:!1})}function qw(){return new nn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ty(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`,blending:gn,depthTest:!1,depthWrite:!1})}function Xw(){return new nn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ty(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`,blending:gn,depthTest:!1,depthWrite:!1})}function ty(){return`

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`}function HB(r){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===Jr||l===lf,h=l===Kr||l===Io;if(c||h){let u=e.get(o);const d=u!==void 0?u.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==d)return t===null&&(t=new ey(r)),u=c?t.fromEquirectangular(o,u):t.fromCubemap(o,u),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),u.texture;if(u!==void 0)return u.texture;{const p=o.image;return c&&p&&p.height>0||h&&p&&n(p)?(t===null&&(t=new ey(r)),u=c?t.fromEquirectangular(o):t.fromCubemap(o),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),o.addEventListener("dispose",s),u.texture):null}}}return o}function n(o){let l=0;const c=6;for(let h=0;h<c;h++)o[h]!==void 0&&l++;return l===c}function s(o){const l=o.target;l.removeEventListener("dispose",s);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:i,dispose:a}}function QB(r){const e={};function t(i){if(e[i]!==void 0)return e[i];let n;switch(i){case"WEBGL_depth_texture":n=r.getExtension("WEBGL_depth_texture")||r.getExtension("MOZ_WEBGL_depth_texture")||r.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=r.getExtension("EXT_texture_filter_anisotropic")||r.getExtension("MOZ_EXT_texture_filter_anisotropic")||r.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=r.getExtension("WEBGL_compressed_texture_s3tc")||r.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||r.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=r.getExtension("WEBGL_compressed_texture_pvrtc")||r.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=r.getExtension(i)}return e[i]=n,n}return{has:function(i){return t(i)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(i){const n=t(i);return n===null&&console.warn("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function jB(r,e,t,i){const n={},s=new WeakMap;function a(u){const d=u.target;d.index!==null&&e.remove(d.index);for(const m in d.attributes)e.remove(d.attributes[m]);for(const m in d.morphAttributes){const A=d.morphAttributes[m];for(let g=0,y=A.length;g<y;g++)e.remove(A[g])}d.removeEventListener("dispose",a),delete n[d.id];const p=s.get(d);p&&(e.remove(p),s.delete(d)),i.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function o(u,d){return n[d.id]===!0||(d.addEventListener("dispose",a),n[d.id]=!0,t.memory.geometries++),d}function l(u){const d=u.attributes;for(const m in d)e.update(d[m],r.ARRAY_BUFFER);const p=u.morphAttributes;for(const m in p){const A=p[m];for(let g=0,y=A.length;g<y;g++)e.update(A[g],r.ARRAY_BUFFER)}}function c(u){const d=[],p=u.index,m=u.attributes.position;let A=0;if(p!==null){const _=p.array;A=p.version;for(let v=0,b=_.length;v<b;v+=3){const T=_[v+0],E=_[v+1],M=_[v+2];d.push(T,E,E,M,M,T)}}else if(m!==void 0){const _=m.array;A=m.version;for(let v=0,b=_.length/3-1;v<b;v+=3){const T=v+0,E=v+1,M=v+2;d.push(T,E,E,M,M,T)}}else return;const g=new(mw(d)?QA:Bf)(d,1);g.version=A;const y=s.get(u);y&&e.remove(y),s.set(u,g)}function h(u){const d=s.get(u);if(d){const p=u.index;p!==null&&d.version<p.version&&c(u)}else c(u);return s.get(u)}return{get:o,update:l,getWireframeAttribute:h}}function WB(r,e,t){let i;function n(u){i=u}let s,a;function o(u){s=u.type,a=u.bytesPerElement}function l(u,d){r.drawElements(i,d,s,u*a),t.update(d,i,1)}function c(u,d,p){p!==0&&(r.drawElementsInstanced(i,d,s,u*a,p),t.update(d,i,p))}function h(u,d,p){if(p===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let A=0;A<p;A++)this.render(u[A]/a,d[A]);else{m.multiDrawElementsWEBGL(i,d,0,s,u,0,p);let A=0;for(let g=0;g<p;g++)A+=d[g];t.update(A,i,1)}}this.setMode=n,this.setIndex=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=h}function qB(r){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,a,o){switch(t.calls++,a){case r.TRIANGLES:t.triangles+=o*(s/3);break;case r.LINES:t.lines+=o*(s/2);break;case r.LINE_STRIP:t.lines+=o*(s-1);break;case r.LINE_LOOP:t.lines+=o*s;break;case r.POINTS:t.points+=o*s;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function n(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:n,update:i}}function XB(r,e,t){const i=new WeakMap,n=new rt;function s(a,o,l){const c=a.morphTargetInfluences,h=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=h!==void 0?h.length:0;let d=i.get(o);if(d===void 0||d.count!==u){let w=function(){M.dispose(),i.delete(o),o.removeEventListener("dispose",w)};d!==void 0&&d.texture.dispose();const p=o.morphAttributes.position!==void 0,m=o.morphAttributes.normal!==void 0,A=o.morphAttributes.color!==void 0,g=o.morphAttributes.position||[],y=o.morphAttributes.normal||[],_=o.morphAttributes.color||[];let v=0;p===!0&&(v=1),m===!0&&(v=2),A===!0&&(v=3);let b=o.attributes.position.count*v,T=1;b>e.maxTextureSize&&(T=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const E=new Float32Array(b*T*4*u),M=new bf(E,b,T,u);M.type=zt,M.needsUpdate=!0;const S=v*4;for(let C=0;C<u;C++){const D=g[C],O=y[C],F=_[C],G=b*T*4*C;for(let j=0;j<D.count;j++){const W=j*S;p===!0&&(n.fromBufferAttribute(D,j),E[G+W+0]=n.x,E[G+W+1]=n.y,E[G+W+2]=n.z,E[G+W+3]=0),m===!0&&(n.fromBufferAttribute(O,j),E[G+W+4]=n.x,E[G+W+5]=n.y,E[G+W+6]=n.z,E[G+W+7]=0),A===!0&&(n.fromBufferAttribute(F,j),E[G+W+8]=n.x,E[G+W+9]=n.y,E[G+W+10]=n.z,E[G+W+11]=F.itemSize===4?n.w:1)}}d={count:u,texture:M,size:new $(b,T)},i.set(o,d),o.addEventListener("dispose",w)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)l.getUniforms().setValue(r,"morphTexture",a.morphTexture,t);else{let p=0;for(let A=0;A<c.length;A++)p+=c[A];const m=o.morphTargetsRelative?1:1-p;l.getUniforms().setValue(r,"morphTargetBaseInfluence",m),l.getUniforms().setValue(r,"morphTargetInfluences",c)}l.getUniforms().setValue(r,"morphTargetsTexture",d.texture,t),l.getUniforms().setValue(r,"morphTargetsTextureSize",d.size)}return{update:s}}function YB(r,e,t,i){let n=new WeakMap;function s(l){const c=i.render.frame,h=l.geometry,u=e.get(l,h);if(n.get(u)!==c&&(e.update(u),n.set(u,c)),l.isInstancedMesh&&(l.hasEventListener("dispose",o)===!1&&l.addEventListener("dispose",o),n.get(l)!==c&&(t.update(l.instanceMatrix,r.ARRAY_BUFFER),l.instanceColor!==null&&t.update(l.instanceColor,r.ARRAY_BUFFER),n.set(l,c))),l.isSkinnedMesh){const d=l.skeleton;n.get(d)!==c&&(d.update(),n.set(d,c))}return u}function a(){n=new WeakMap}function o(l){const c=l.target;c.removeEventListener("dispose",o),t.remove(c.instanceMatrix),c.instanceColor!==null&&t.remove(c.instanceColor)}return{update:s,dispose:a}}class jf extends Rt{constructor(e,t,i,n,s,a,o,l,c,h){if(h=h!==void 0?h:Do,h!==Do&&h!==Zh)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");i===void 0&&h===Do&&(i=ea),i===void 0&&h===Zh&&(i=$l),super(null,n,s,a,o,l,h,i,c),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=o!==void 0?o:pi,this.minFilter=l!==void 0?l:pi,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}const Yw=new Rt,$w=new jf(1,1);$w.compareFunction=dw;const Kw=new bf,Jw=new wf,Zw=new _c,eC=[],tC=[],iC=new Float32Array(16),nC=new Float32Array(9),sC=new Float32Array(4);function Cc(r,e,t){const i=r[0];if(i<=0||i>0)return r;const n=e*t;let s=eC[n];if(s===void 0&&(s=new Float32Array(n),eC[n]=s),e!==0){i.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,r[a].toArray(s,o)}return s}function An(r,e){if(r.length!==e.length)return!1;for(let t=0,i=r.length;t<i;t++)if(r[t]!==e[t])return!1;return!0}function yn(r,e){for(let t=0,i=e.length;t<i;t++)r[t]=e[t]}function Wf(r,e){let t=tC[e];t===void 0&&(t=new Int32Array(e),tC[e]=t);for(let i=0;i!==e;++i)t[i]=r.allocateTextureUnit();return t}function $B(r,e){const t=this.cache;t[0]!==e&&(r.uniform1f(this.addr,e),t[0]=e)}function KB(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(An(t,e))return;r.uniform2fv(this.addr,e),yn(t,e)}}function JB(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(r.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(An(t,e))return;r.uniform3fv(this.addr,e),yn(t,e)}}function ZB(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(An(t,e))return;r.uniform4fv(this.addr,e),yn(t,e)}}function e2(r,e){const t=this.cache,i=e.elements;if(i===void 0){if(An(t,e))return;r.uniformMatrix2fv(this.addr,!1,e),yn(t,e)}else{if(An(t,i))return;sC.set(i),r.uniformMatrix2fv(this.addr,!1,sC),yn(t,i)}}function t2(r,e){const t=this.cache,i=e.elements;if(i===void 0){if(An(t,e))return;r.uniformMatrix3fv(this.addr,!1,e),yn(t,e)}else{if(An(t,i))return;nC.set(i),r.uniformMatrix3fv(this.addr,!1,nC),yn(t,i)}}function i2(r,e){const t=this.cache,i=e.elements;if(i===void 0){if(An(t,e))return;r.uniformMatrix4fv(this.addr,!1,e),yn(t,e)}else{if(An(t,i))return;iC.set(i),r.uniformMatrix4fv(this.addr,!1,iC),yn(t,i)}}function n2(r,e){const t=this.cache;t[0]!==e&&(r.uniform1i(this.addr,e),t[0]=e)}function s2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(An(t,e))return;r.uniform2iv(this.addr,e),yn(t,e)}}function r2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(An(t,e))return;r.uniform3iv(this.addr,e),yn(t,e)}}function a2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(An(t,e))return;r.uniform4iv(this.addr,e),yn(t,e)}}function o2(r,e){const t=this.cache;t[0]!==e&&(r.uniform1ui(this.addr,e),t[0]=e)}function l2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(An(t,e))return;r.uniform2uiv(this.addr,e),yn(t,e)}}function c2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(An(t,e))return;r.uniform3uiv(this.addr,e),yn(t,e)}}function h2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(An(t,e))return;r.uniform4uiv(this.addr,e),yn(t,e)}}function u2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n);const s=this.type===r.SAMPLER_2D_SHADOW?$w:Yw;t.setTexture2D(e||s,n)}function d2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n),t.setTexture3D(e||Jw,n)}function f2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n),t.setTextureCube(e||Zw,n)}function p2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n),t.setTexture2DArray(e||Kw,n)}function m2(r){switch(r){case 5126:return $B;case 35664:return KB;case 35665:return JB;case 35666:return ZB;case 35674:return e2;case 35675:return t2;case 35676:return i2;case 5124:case 35670:return n2;case 35667:case 35671:return s2;case 35668:case 35672:return r2;case 35669:case 35673:return a2;case 5125:return o2;case 36294:return l2;case 36295:return c2;case 36296:return h2;case 35678:case 36198:case 36298:case 36306:case 35682:return u2;case 35679:case 36299:case 36307:return d2;case 35680:case 36300:case 36308:case 36293:return f2;case 36289:case 36303:case 36311:case 36292:return p2}}function g2(r,e){r.uniform1fv(this.addr,e)}function A2(r,e){const t=Cc(e,this.size,2);r.uniform2fv(this.addr,t)}function y2(r,e){const t=Cc(e,this.size,3);r.uniform3fv(this.addr,t)}function v2(r,e){const t=Cc(e,this.size,4);r.uniform4fv(this.addr,t)}function _2(r,e){const t=Cc(e,this.size,4);r.uniformMatrix2fv(this.addr,!1,t)}function b2(r,e){const t=Cc(e,this.size,9);r.uniformMatrix3fv(this.addr,!1,t)}function w2(r,e){const t=Cc(e,this.size,16);r.uniformMatrix4fv(this.addr,!1,t)}function C2(r,e){r.uniform1iv(this.addr,e)}function x2(r,e){r.uniform2iv(this.addr,e)}function S2(r,e){r.uniform3iv(this.addr,e)}function E2(r,e){r.uniform4iv(this.addr,e)}function M2(r,e){r.uniform1uiv(this.addr,e)}function T2(r,e){r.uniform2uiv(this.addr,e)}function I2(r,e){r.uniform3uiv(this.addr,e)}function P2(r,e){r.uniform4uiv(this.addr,e)}function D2(r,e,t){const i=this.cache,n=e.length,s=Wf(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTexture2D(e[a]||Yw,s[a])}function R2(r,e,t){const i=this.cache,n=e.length,s=Wf(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTexture3D(e[a]||Jw,s[a])}function B2(r,e,t){const i=this.cache,n=e.length,s=Wf(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTextureCube(e[a]||Zw,s[a])}function L2(r,e,t){const i=this.cache,n=e.length,s=Wf(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTexture2DArray(e[a]||Kw,s[a])}function O2(r){switch(r){case 5126:return g2;case 35664:return A2;case 35665:return y2;case 35666:return v2;case 35674:return _2;case 35675:return b2;case 35676:return w2;case 5124:case 35670:return C2;case 35667:case 35671:return x2;case 35668:case 35672:return S2;case 35669:case 35673:return E2;case 5125:return M2;case 36294:return T2;case 36295:return I2;case 36296:return P2;case 35678:case 36198:case 36298:case 36306:case 35682:return D2;case 35679:case 36299:case 36307:return R2;case 35680:case 36300:case 36308:case 36293:return B2;case 36289:case 36303:case 36311:case 36292:return L2}}class U2{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=m2(t.type)}}class F2{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=O2(t.type)}}class N2{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const n=this.seq;for(let s=0,a=n.length;s!==a;++s){const o=n[s];o.setValue(e,t[o.id],i)}}}const iy=/(\w+)(\])?(\[|\.)?/g;function rC(r,e){r.seq.push(e),r.map[e.id]=e}function k2(r,e,t){const i=r.name,n=i.length;for(iy.lastIndex=0;;){const s=iy.exec(i),a=iy.lastIndex;let o=s[1];const l=s[2]==="]",c=s[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===n){rC(t,c===void 0?new U2(o,r,e):new F2(o,r,e));break}else{let u=t.map[o];u===void 0&&(u=new N2(o),rC(t,u)),t=u}}}class qf{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const s=e.getActiveUniform(t,n),a=e.getUniformLocation(t,s.name);k2(s,a,this)}}setValue(e,t,i,n){const s=this.map[t];s!==void 0&&s.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];n!==void 0&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let s=0,a=t.length;s!==a;++s){const o=t[s],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,s=e.length;n!==s;++n){const a=e[n];a.id in t&&i.push(a)}return i}}function aC(r,e,t){const i=r.createShader(e);return r.shaderSource(i,t),r.compileShader(i),i}const G2=37297;let z2=0;function V2(r,e){const t=r.split(`
`),i=[],n=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let a=n;a<s;a++){const o=a+1;i.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return i.join(`
`)}function H2(r){const e=Xt.getPrimaries(Xt.workingColorSpace),t=r===si||r===Gs?null:Xt.getPrimaries(r);let i;switch(e===t||!t?i="":e===gf&&t===mf?i="LinearDisplayP3ToLinearSRGB":e===mf&&t===gf&&(i="LinearSRGBToLinearDisplayP3"),r){case si:return["",""];case Dt:case tu:return[i,"LinearTransferOETF"];case vt:case eu:return[i,"sRGBTransferOETF"];case Gs:return["","LinearToRGBM16"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",r),[i,"LinearTransferOETF"]}}function oC(r,e,t){const i=r.getShaderParameter(e,r.COMPILE_STATUS),n=r.getShaderInfoLog(e).trim();if(i&&n==="")return"";const s=/ERROR: 0:(\d+)/.exec(n);if(s){const a=parseInt(s[1]);return t.toUpperCase()+`

`+n+`

`+V2(r.getShaderSource(e),a)}else return n}function Q2(r,e){let t;switch(e){case Dt:t="";break;case vt:t="sRGBToLinear";break;case Gs:t="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",e),t="";break}return`vec4 ${r}( vec4 value ) { return ${t} ( value ); }`}function j2(r,e){const t=H2(e);return`vec4 ${r}( vec4 value ) { return ${t[0]}( ${t[1]}( value ) ); }`}function W2(r,e){let t;switch(e){case Rb:t="Linear";break;case Bb:t="Reinhard";break;case Lb:t="OptimizedCineon";break;case aA:t="ACESFilmic";break;case Ub:t="AgX";break;case CP:t="Neutral";break;case Ob:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+r+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function q2(r){return[r.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",r.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(uu).join(`
`)}function X2(r){const e=[];for(const t in r){const i=r[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(`
`)}function Y2(r,e){const t={},i=r.getProgramParameter(e,r.ACTIVE_ATTRIBUTES);for(let n=0;n<i;n++){const s=r.getActiveAttrib(e,n),a=s.name;let o=1;s.type===r.FLOAT_MAT2&&(o=2),s.type===r.FLOAT_MAT3&&(o=3),s.type===r.FLOAT_MAT4&&(o=4),t[a]={type:s.type,location:r.getAttribLocation(e,a),locationSize:o}}return t}function uu(r){return r!==""}function lC(r,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return r.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,t).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 cC(r,e){return r.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const $2=/^[ \t]*#include +<([\w\d./]+)>/gm;function ny(r){return r.replace($2,J2)}const K2=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function J2(r,e){let t=ot[e];if(t===void 0){const i=K2.get(e);if(i!==void 0)t=ot[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return ny(t)}const Z2=/#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 hC(r){return r.replace(Z2,eL)}function eL(r,e,t,i){let n="";for(let s=parseInt(e);s<parseInt(t);s++)n+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return n}function uC(r){let e=`precision ${r.precision} float;
	precision ${r.precision} int;
	precision ${r.precision} sampler2D;
	precision ${r.precision} samplerCube;
	precision ${r.precision} sampler3D;
	precision ${r.precision} sampler2DArray;
	precision ${r.precision} sampler2DShadow;
	precision ${r.precision} samplerCubeShadow;
	precision ${r.precision} sampler2DArrayShadow;
	precision ${r.precision} isampler2D;
	precision ${r.precision} isampler3D;
	precision ${r.precision} isamplerCube;
	precision ${r.precision} isampler2DArray;
	precision ${r.precision} usampler2D;
	precision ${r.precision} usampler3D;
	precision ${r.precision} usamplerCube;
	precision ${r.precision} usampler2DArray;
	`;return r.precision==="highp"?e+=`
#define HIGH_PRECISION`:r.precision==="mediump"?e+=`
#define MEDIUM_PRECISION`:r.precision==="lowp"&&(e+=`
#define LOW_PRECISION`),e}function tL(r){let e="SHADOWMAP_TYPE_BASIC";return r.shadowMapType===Kg?e="SHADOWMAP_TYPE_PCF":r.shadowMapType===_P?e="SHADOWMAP_TYPE_PCF_SOFT":r.shadowMapType===Yr&&(e="SHADOWMAP_TYPE_VSM"),e}function iL(r){let e="ENVMAP_TYPE_CUBE";if(r.envMap)switch(r.envMapMode){case Kr:case Io:e="ENVMAP_TYPE_CUBE";break;case Yl:e="ENVMAP_TYPE_CUBE_UV";break}return e}function nL(r){let e="ENVMAP_MODE_REFLECTION";if(r.envMap)switch(r.envMapMode){case Io:e="ENVMAP_MODE_REFRACTION";break}return e}function sL(r){let e="ENVMAP_BLENDING_NONE";if(r.envMap)switch(r.combine){case Xl:e="ENVMAP_BLENDING_MULTIPLY";break;case bP:e="ENVMAP_BLENDING_MIX";break;case wP:e="ENVMAP_BLENDING_ADD";break}return e}function rL(r){const e=r.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,i=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:i,maxMip:t}}function aL(r,e,t,i){const n=r.getContext(),s=t.defines;let a=t.vertexShader,o=t.fragmentShader;const l=tL(t),c=iL(t),h=nL(t),u=sL(t),d=rL(t),p=q2(t),m=X2(s),A=n.createProgram();let g,y,_=t.glslVersion?"#version "+t.glslVersion+`
`:"";t.isRawShaderMaterial?(g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(uu).join(`
`),g.length>0&&(g+=`
`),y=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(uu).join(`
`),y.length>0&&(y+=`
`)):(g=[uC(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","	attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","	attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","	uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","	attribute vec2 uv1;","#endif","#ifdef USE_UV2","	attribute vec2 uv2;","#endif","#ifdef USE_UV3","	attribute vec2 uv3;","#endif","#ifdef USE_TANGENT","	attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","	attribute vec4 color;","#elif defined( USE_COLOR )","	attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","	attribute vec3 morphTarget0;","	attribute vec3 morphTarget1;","	attribute vec3 morphTarget2;","	attribute vec3 morphTarget3;","	#ifdef USE_MORPHNORMALS","		attribute vec3 morphNormal0;","		attribute vec3 morphNormal1;","		attribute vec3 morphNormal2;","		attribute vec3 morphNormal3;","	#else","		attribute vec3 morphTarget4;","		attribute vec3 morphTarget5;","		attribute vec3 morphTarget6;","		attribute vec3 morphTarget7;","	#endif","#endif","#ifdef USE_SKINNING","	attribute vec4 skinIndex;","	attribute vec4 skinWeight;","#endif",`
`].filter(uu).join(`
`),y=[uC(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.useLegacyLights?"#define LEGACY_LIGHTS":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==$r?"#define TONE_MAPPING":"",t.toneMapping!==$r?ot.tonemapping_pars_fragment:"",t.toneMapping!==$r?W2("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ot.colorspace_pars_fragment,j2("linearToOutputTexel",t.outputColorSpace),t.transmissionSamplerMapEncoding?Q2("transmissionSamplerMapTexelToLinear",t.transmissionSamplerMapEncoding):"",t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(uu).join(`
`)),a=ny(a),a=lC(a,t),a=cC(a,t),o=ny(o),o=lC(o,t),o=cC(o,t),a=hC(a),o=hC(o),t.isRawShaderMaterial!==!0&&(_=`#version 300 es
`,g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+g,y=["#define varying in",t.glslVersion===EA?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===EA?"":"#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","#define WebGL2Context 1"].join(`
`)+`
`+y);const v=_+g+a,b=_+y+o,T=aC(n,n.VERTEX_SHADER,v),E=aC(n,n.FRAGMENT_SHADER,b);n.attachShader(A,T),n.attachShader(A,E),t.index0AttributeName!==void 0?n.bindAttribLocation(A,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(A,0,"position"),n.linkProgram(A);function M(D){if(r.debug.checkShaderErrors){const O=n.getProgramInfoLog(A).trim(),F=n.getShaderInfoLog(T).trim(),G=n.getShaderInfoLog(E).trim();let j=!0,W=!0;if(n.getProgramParameter(A,n.LINK_STATUS)===!1)if(j=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(n,A,T,E);else{const K=oC(n,T,"vertex"),q=oC(n,E,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(A,n.VALIDATE_STATUS)+`

Material Name: `+D.name+`
Material Type: `+D.type+`

Program Info Log: `+O+`
`+K+`
`+q)}else O!==""?console.warn("THREE.WebGLProgram: Program Info Log:",O):(F===""||G==="")&&(W=!1);W&&(D.diagnostics={runnable:j,programLog:O,vertexShader:{log:F,prefix:g},fragmentShader:{log:G,prefix:y}})}n.deleteShader(T),n.deleteShader(E),S=new qf(n,A),w=Y2(n,A)}let S;this.getUniforms=function(){return S===void 0&&M(this),S};let w;this.getAttributes=function(){return w===void 0&&M(this),w};let C=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return C===!1&&(C=n.getProgramParameter(A,G2)),C},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(A),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=z2++,this.cacheKey=e,this.usedTimes=1,this.program=A,this.vertexShader=T,this.fragmentShader=E,this}let oL=0;class lL{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),s=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(n)===!1&&(a.add(n),n.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new cL(e),t.set(e,i)),i}}class cL{constructor(e){this.id=oL++,this.code=e,this.usedTimes=0}}function hL(r,e,t,i,n,s,a){const o=new If,l=new lL,c=new Set,h=[],u=n.logarithmicDepthBuffer,d=n.vertexTextures;let p=n.precision;const m={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 A(w){return c.add(w),w===0?"uv":`uv${w}`}function g(w,C,D,O,F){const G=O.fog,j=F.geometry,W=w.isMeshStandardMaterial?O.environment:null,K=(w.isMeshStandardMaterial?t:e).get(w.envMap||W),q=K&&K.mapping===Yl?K.image.height:null,oe=m[w.type];w.precision!==null&&(p=n.getMaxPrecision(w.precision),p!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",p,"instead."));const re=j.morphAttributes.position||j.morphAttributes.normal||j.morphAttributes.color,Ce=re!==void 0?re.length:0;let Ie=0;j.morphAttributes.position!==void 0&&(Ie=1),j.morphAttributes.normal!==void 0&&(Ie=2),j.morphAttributes.color!==void 0&&(Ie=3);let Ue,te,ce,me;if(oe){const ii=Di[oe];Ue=ii.vertexShader,te=ii.fragmentShader}else Ue=w.vertexShader,te=w.fragmentShader,l.update(w),ce=l.getVertexShaderID(w),me=l.getFragmentShaderID(w);const we=r.getRenderTarget(),je=r.userData&&r.userData.transmissionRenderTarget,ht=F.isInstancedMesh===!0,Ze=F.isBatchedMesh===!0,Y=!!w.map,fe=!!w.matcap,he=!!K,Se=!!w.aoMap,Ee=!!w.lightMap,De=!!w.bumpMap,N=!!w.normalMap,B=!!w.displacementMap,J=!!w.emissiveMap,le=!!w.metalnessMap,ue=!!w.roughnessMap,ve=w.anisotropy>0,Ke=w.clearcoat>0,be=w.iridescence>0,Ye=w.sheen>0,at=w.transmission>0,Be=ve&&!!w.anisotropyMap,Ne=Ke&&!!w.clearcoatMap,dt=Ke&&!!w.clearcoatNormalMap,We=Ke&&!!w.clearcoatRoughnessMap,qe=be&&!!w.iridescenceMap,Ft=be&&!!w.iridescenceThicknessMap,yt=Ye&&!!w.sheenColorMap,Mt=Ye&&!!w.sheenRoughnessMap,Qt=!!w.specularMap,Nt=!!w.specularColorMap,ze=!!w.specularIntensityMap,I=at&&!!w.transmissionMap,ie=at&&!!w.thicknessMap,X=!!w.gradientMap,Pe=!!w.alphaMap,Ve=w.alphaTest>0,jt=!!w.alphaHash,Ot=!!w.extensions;let Si=$r;w.toneMapped&&(we===null||we.isXRRenderTarget===!0)&&(Si=r.toneMapping);const hn={shaderID:oe,shaderType:w.type,shaderName:w.name,vertexShader:Ue,fragmentShader:te,defines:w.defines,customVertexShaderID:ce,customFragmentShaderID:me,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:p,batching:Ze,instancing:ht,instancingColor:ht&&F.instanceColor!==null,instancingMorph:ht&&F.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:we===null?r.outputColorSpace:we.isXRRenderTarget===!0||we.texture.colorSpace&&we.texture.colorSpace!==vt?we.texture.colorSpace:Dt,alphaToCoverage:!!w.alphaToCoverage,map:Y,matcap:fe,envMap:he,envMapMode:he&&K.mapping,envMapCubeUVHeight:q,aoMap:Se,lightMap:Ee,bumpMap:De,normalMap:N,displacementMap:d&&B,emissiveMap:J,normalMapObjectSpace:N&&w.normalMapType===uw,normalMapTangentSpace:N&&w.normalMapType===ks,metalnessMap:le,roughnessMap:ue,anisotropy:ve,anisotropyMap:Be,clearcoat:Ke,clearcoatMap:Ne,clearcoatNormalMap:dt,clearcoatRoughnessMap:We,iridescence:be,iridescenceMap:qe,iridescenceThicknessMap:Ft,sheen:Ye,sheenColorMap:yt,sheenRoughnessMap:Mt,specularMap:Qt,specularColorMap:Nt,specularIntensityMap:ze,transmission:at,transmissionMap:I,thicknessMap:ie,transmissionSamplerMapEncoding:je&&je.texture.colorSpace||Dt,gradientMap:X,opaque:w.transparent===!1&&w.blending===xr&&w.alphaToCoverage===!1&&!(w.transmission>0),alphaMap:Pe,alphaTest:Ve,alphaHash:jt,combine:w.combine,mapUv:Y&&A(w.map.channel),aoMapUv:Se&&A(w.aoMap.channel),lightMapUv:Ee&&A(w.lightMap.channel),bumpMapUv:De&&A(w.bumpMap.channel),normalMapUv:N&&A(w.normalMap.channel),displacementMapUv:B&&A(w.displacementMap.channel),emissiveMapUv:J&&A(w.emissiveMap.channel),metalnessMapUv:le&&A(w.metalnessMap.channel),roughnessMapUv:ue&&A(w.roughnessMap.channel),anisotropyMapUv:Be&&A(w.anisotropyMap.channel),clearcoatMapUv:Ne&&A(w.clearcoatMap.channel),clearcoatNormalMapUv:dt&&A(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:We&&A(w.clearcoatRoughnessMap.channel),iridescenceMapUv:qe&&A(w.iridescenceMap.channel),iridescenceThicknessMapUv:Ft&&A(w.iridescenceThicknessMap.channel),sheenColorMapUv:yt&&A(w.sheenColorMap.channel),sheenRoughnessMapUv:Mt&&A(w.sheenRoughnessMap.channel),specularMapUv:Qt&&A(w.specularMap.channel),specularColorMapUv:Nt&&A(w.specularColorMap.channel),specularIntensityMapUv:ze&&A(w.specularIntensityMap.channel),transmissionMapUv:I&&A(w.transmissionMap.channel),thicknessMapUv:ie&&A(w.thicknessMap.channel),alphaMapUv:Pe&&A(w.alphaMap.channel),vertexTangents:!!j.attributes.tangent&&(N||ve||j.userData.__forceUseTangent),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!j.attributes.color&&j.attributes.color.itemSize===4,pointsUvs:F.isPoints===!0&&!!j.attributes.uv&&(Y||Pe),fog:!!G,useFog:w.fog===!0,fogExp2:!!G&&G.isFogExp2,flatShading:w.flatShading===!0,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:u,skinning:F.isSkinnedMesh===!0,morphTargets:j.morphAttributes.position!==void 0,morphNormals:j.morphAttributes.normal!==void 0,morphColors:j.morphAttributes.color!==void 0,morphTargetsCount:Ce,morphTextureStride:Ie,numDirLights:C.directional.length,numPointLights:C.point.length,numSpotLights:C.spot.length,numSpotLightMaps:C.spotLightMap.length,numRectAreaLights:C.rectArea.length,numHemiLights:C.hemi.length,numDirLightShadows:C.directionalShadowMap.length,numPointLightShadows:C.pointShadowMap.length,numSpotLightShadows:C.spotShadowMap.length,numSpotLightShadowsWithMaps:C.numSpotLightShadowsWithMaps,numLightProbes:C.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:w.dithering,shadowMapEnabled:r.shadowMap.enabled&&D.length>0,shadowMapType:r.shadowMap.type,toneMapping:Si,useLegacyLights:r._useLegacyLights,decodeVideoTexture:Y&&w.map.isVideoTexture===!0&&Xt.getTransfer(w.map.colorSpace)===bi,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===Zi,flipSided:w.side===Rn,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:Ot&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:Ot&&w.extensions.multiDraw===!0&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return hn.vertexUv1s=c.has(1),hn.vertexUv2s=c.has(2),hn.vertexUv3s=c.has(3),c.clear(),hn}function y(w){const C=[];if(w.shaderID?C.push(w.shaderID):(C.push(w.customVertexShaderID),C.push(w.customFragmentShaderID)),w.defines!==void 0)for(const D in w.defines)C.push(D),C.push(w.defines[D]);return w.isRawShaderMaterial===!1&&(_(C,w),v(C,w),C.push(r.outputColorSpace)),C.push(w.customProgramCacheKey),C.join()}function _(w,C){w.push(C.precision),w.push(C.outputColorSpace),w.push(C.envMapMode),w.push(C.envMapCubeUVHeight),w.push(C.mapUv),w.push(C.alphaMapUv),w.push(C.lightMapUv),w.push(C.aoMapUv),w.push(C.bumpMapUv),w.push(C.normalMapUv),w.push(C.displacementMapUv),w.push(C.emissiveMapUv),w.push(C.metalnessMapUv),w.push(C.roughnessMapUv),w.push(C.anisotropyMapUv),w.push(C.clearcoatMapUv),w.push(C.clearcoatNormalMapUv),w.push(C.clearcoatRoughnessMapUv),w.push(C.iridescenceMapUv),w.push(C.iridescenceThicknessMapUv),w.push(C.sheenColorMapUv),w.push(C.sheenRoughnessMapUv),w.push(C.specularMapUv),w.push(C.specularColorMapUv),w.push(C.specularIntensityMapUv),w.push(C.transmissionMapUv),w.push(C.thicknessMapUv),w.push(C.combine),w.push(C.fogExp2),w.push(C.sizeAttenuation),w.push(C.morphTargetsCount),w.push(C.morphAttributeCount),w.push(C.numDirLights),w.push(C.numPointLights),w.push(C.numSpotLights),w.push(C.numSpotLightMaps),w.push(C.numHemiLights),w.push(C.numRectAreaLights),w.push(C.numDirLightShadows),w.push(C.numPointLightShadows),w.push(C.numSpotLightShadows),w.push(C.numSpotLightShadowsWithMaps),w.push(C.numLightProbes),w.push(C.shadowMapType),w.push(C.toneMapping),w.push(C.numClippingPlanes),w.push(C.numClipIntersection),w.push(C.depthPacking)}function v(w,C){o.disableAll(),C.supportsVertexTextures&&o.enable(0),C.instancing&&o.enable(1),C.instancingColor&&o.enable(2),C.instancingMorph&&o.enable(3),C.matcap&&o.enable(4),C.envMap&&o.enable(5),C.normalMapObjectSpace&&o.enable(6),C.normalMapTangentSpace&&o.enable(7),C.clearcoat&&o.enable(8),C.iridescence&&o.enable(9),C.alphaTest&&o.enable(10),C.vertexColors&&o.enable(11),C.vertexAlphas&&o.enable(12),C.vertexUv1s&&o.enable(13),C.vertexUv2s&&o.enable(14),C.vertexUv3s&&o.enable(15),C.vertexTangents&&o.enable(16),C.anisotropy&&o.enable(17),C.alphaHash&&o.enable(18),C.batching&&o.enable(19),w.push(o.mask),o.disableAll(),C.fog&&o.enable(0),C.useFog&&o.enable(1),C.flatShading&&o.enable(2),C.logarithmicDepthBuffer&&o.enable(3),C.skinning&&o.enable(4),C.morphTargets&&o.enable(5),C.morphNormals&&o.enable(6),C.morphColors&&o.enable(7),C.premultipliedAlpha&&o.enable(8),C.shadowMapEnabled&&o.enable(9),C.useLegacyLights&&o.enable(10),C.doubleSided&&o.enable(11),C.flipSided&&o.enable(12),C.useDepthPacking&&o.enable(13),C.dithering&&o.enable(14),C.transmission&&o.enable(15),C.sheen&&o.enable(16),C.opaque&&o.enable(17),C.pointsUvs&&o.enable(18),C.decodeVideoTexture&&o.enable(19),C.alphaToCoverage&&o.enable(20),w.push(o.mask)}function b(w){const C=m[w.type];let D;if(C){const O=Di[C];D=ko.clone(O.uniforms)}else D=w.uniforms;return D}function T(w,C){let D;for(let O=0,F=h.length;O<F;O++){const G=h[O];if(G.cacheKey===C){D=G,++D.usedTimes;break}}return D===void 0&&(D=new aL(r,C,w,s),h.push(D)),D}function E(w){if(--w.usedTimes===0){const C=h.indexOf(w);h[C]=h[h.length-1],h.pop(),w.destroy()}}function M(w){l.remove(w)}function S(){l.dispose()}return{getParameters:g,getProgramCacheKey:y,getUniforms:b,acquireProgram:T,releaseProgram:E,releaseShaderCache:M,programs:h,dispose:S}}function uL(){let r=new WeakMap;function e(s){let a=r.get(s);return a===void 0&&(a={},r.set(s,a)),a}function t(s){r.delete(s)}function i(s,a,o){r.get(s)[a]=o}function n(){r=new WeakMap}return{get:e,remove:t,update:i,dispose:n}}function dL(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.material.id!==e.material.id?r.material.id-e.material.id:r.z!==e.z?r.z-e.z:r.id-e.id}function dC(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function fC(){const r=[];let e=0;const t=[],i=[],n=[];function s(){e=0,t.length=0,i.length=0,n.length=0}function a(u,d,p,m,A,g){let y=r[e];return y===void 0?(y={id:u.id,object:u,geometry:d,material:p,groupOrder:m,renderOrder:u.renderOrder,z:A,group:g},r[e]=y):(y.id=u.id,y.object=u,y.geometry=d,y.material=p,y.groupOrder=m,y.renderOrder=u.renderOrder,y.z=A,y.group=g),e++,y}function o(u,d,p,m,A,g){const y=a(u,d,p,m,A,g);p.transmission>0?i.push(y):p.transparent===!0?n.push(y):t.push(y)}function l(u,d,p,m,A,g){const y=a(u,d,p,m,A,g);p.transmission>0?i.unshift(y):p.transparent===!0?n.unshift(y):t.unshift(y)}function c(u,d){t.length>1&&t.sort(u||dL),i.length>1&&i.sort(d||dC),n.length>1&&n.sort(d||dC)}function h(){for(let u=e,d=r.length;u<d;u++){const p=r[u];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:t,transmissive:i,transparent:n,init:s,push:o,unshift:l,finish:h,sort:c}}function fL(){let r=new WeakMap;function e(i,n){const s=r.get(i);let a;return s===void 0?(a=new fC,r.set(i,[a])):n>=s.length?(a=new fC,s.push(a)):a=s[n],a}function t(){r=new WeakMap}return{get:e,dispose:t}}function pL(){const r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new x,color:new se};break;case"SpotLight":t={position:new x,direction:new x,color:new se,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new x,color:new se,distance:0,decay:0};break;case"HemisphereLight":t={direction:new x,skyColor:new se,groundColor:new se};break;case"RectAreaLight":t={color:new se,position:new x,halfWidth:new x,halfHeight:new x};break}return r[e.id]=t,t}}}function mL(){const r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new $};break;case"SpotLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new $};break;case"PointLight":t={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new $,shadowCameraNear:1,shadowCameraFar:1e3};break}return r[e.id]=t,t}}}let gL=0;function AL(r,e){return(e.castShadow?2:0)-(r.castShadow?2:0)+(e.map?1:0)-(r.map?1:0)}function yL(r){const e=new pL,t=mL(),i={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 c=0;c<9;c++)i.probe.push(new x);const n=new x,s=new pe,a=new pe;function o(c,h){let u=0,d=0,p=0;for(let D=0;D<9;D++)i.probe[D].set(0,0,0);let m=0,A=0,g=0,y=0,_=0,v=0,b=0,T=0,E=0,M=0,S=0;c.sort(AL);const w=h===!0?Math.PI:1;for(let D=0,O=c.length;D<O;D++){const F=c[D],G=F.color,j=F.intensity,W=F.distance,K=F.shadow&&F.shadow.map?F.shadow.map.texture:null;if(F.isAmbientLight)u+=G.r*j*w,d+=G.g*j*w,p+=G.b*j*w;else if(F.isLightProbe){for(let q=0;q<9;q++)i.probe[q].addScaledVector(F.sh.coefficients[q],j);S++}else if(F.isDirectionalLight){const q=e.get(F);if(q.color.copy(F.color).multiplyScalar(F.intensity*w),F.castShadow){const oe=F.shadow,re=t.get(F);re.shadowBias=oe.bias,re.shadowNormalBias=oe.normalBias,re.shadowRadius=oe.radius,re.shadowMapSize=oe.mapSize,i.directionalShadow[m]=re,i.directionalShadowMap[m]=K,i.directionalShadowMatrix[m]=F.shadow.matrix,v++}i.directional[m]=q,m++}else if(F.isSpotLight){const q=e.get(F);q.position.setFromMatrixPosition(F.matrixWorld),q.color.copy(G).multiplyScalar(j*w),q.distance=W,q.coneCos=Math.cos(F.angle),q.penumbraCos=Math.cos(F.angle*(1-F.penumbra)),q.decay=F.decay,i.spot[g]=q;const oe=F.shadow;if(F.map&&(i.spotLightMap[E]=F.map,E++,oe.updateMatrices(F),F.castShadow&&M++),i.spotLightMatrix[g]=oe.matrix,F.castShadow){const re=t.get(F);re.shadowBias=oe.bias,re.shadowNormalBias=oe.normalBias,re.shadowRadius=oe.radius,re.shadowMapSize=oe.mapSize,i.spotShadow[g]=re,i.spotShadowMap[g]=K,T++}g++}else if(F.isRectAreaLight){const q=e.get(F);q.color.copy(G).multiplyScalar(j),q.halfWidth.set(F.width*.5,0,0),q.halfHeight.set(0,F.height*.5,0),i.rectArea[y]=q,y++}else if(F.isPointLight){const q=e.get(F);if(q.color.copy(F.color).multiplyScalar(F.intensity*w),q.distance=F.distance,q.decay=F.decay,F.castShadow){const oe=F.shadow,re=t.get(F);re.shadowBias=oe.bias,re.shadowNormalBias=oe.normalBias,re.shadowRadius=oe.radius,re.shadowMapSize=oe.mapSize,re.shadowCameraNear=oe.camera.near,re.shadowCameraFar=oe.camera.far,i.pointShadow[A]=re,i.pointShadowMap[A]=K,i.pointShadowMatrix[A]=F.shadow.matrix,b++}i.point[A]=q,A++}else if(F.isHemisphereLight){const q=e.get(F);q.skyColor.copy(F.color).multiplyScalar(j*w),q.groundColor.copy(F.groundColor).multiplyScalar(j*w),i.hemi[_]=q,_++}}y>0&&(r.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Re.LTC_FLOAT_1,i.rectAreaLTC2=Re.LTC_FLOAT_2):(i.rectAreaLTC1=Re.LTC_HALF_1,i.rectAreaLTC2=Re.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=p;const C=i.hash;(C.directionalLength!==m||C.pointLength!==A||C.spotLength!==g||C.rectAreaLength!==y||C.hemiLength!==_||C.numDirectionalShadows!==v||C.numPointShadows!==b||C.numSpotShadows!==T||C.numSpotMaps!==E||C.numLightProbes!==S)&&(i.directional.length=m,i.spot.length=g,i.rectArea.length=y,i.point.length=A,i.hemi.length=_,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=b,i.pointShadowMap.length=b,i.spotShadow.length=T,i.spotShadowMap.length=T,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=b,i.spotLightMatrix.length=T+E-M,i.spotLightMap.length=E,i.numSpotLightShadowsWithMaps=M,i.numLightProbes=S,C.directionalLength=m,C.pointLength=A,C.spotLength=g,C.rectAreaLength=y,C.hemiLength=_,C.numDirectionalShadows=v,C.numPointShadows=b,C.numSpotShadows=T,C.numSpotMaps=E,C.numLightProbes=S,i.version=gL++)}function l(c,h){let u=0,d=0,p=0,m=0,A=0;const g=h.matrixWorldInverse;for(let y=0,_=c.length;y<_;y++){const v=c[y];if(v.isDirectionalLight){const b=i.directional[u];b.direction.setFromMatrixPosition(v.matrixWorld),n.setFromMatrixPosition(v.target.matrixWorld),b.direction.sub(n),b.direction.transformDirection(g),u++}else if(v.isSpotLight){const b=i.spot[p];b.position.setFromMatrixPosition(v.matrixWorld),b.position.applyMatrix4(g),b.direction.setFromMatrixPosition(v.matrixWorld),n.setFromMatrixPosition(v.target.matrixWorld),b.direction.sub(n),b.direction.transformDirection(g),p++}else if(v.isRectAreaLight){const b=i.rectArea[m];b.position.setFromMatrixPosition(v.matrixWorld),b.position.applyMatrix4(g),a.identity(),s.copy(v.matrixWorld),s.premultiply(g),a.extractRotation(s),b.halfWidth.set(v.width*.5,0,0),b.halfHeight.set(0,v.height*.5,0),b.halfWidth.applyMatrix4(a),b.halfHeight.applyMatrix4(a),m++}else if(v.isPointLight){const b=i.point[d];b.position.setFromMatrixPosition(v.matrixWorld),b.position.applyMatrix4(g),d++}else if(v.isHemisphereLight){const b=i.hemi[A];b.direction.setFromMatrixPosition(v.matrixWorld),b.direction.transformDirection(g),A++}}}return{setup:o,setupView:l,state:i}}function pC(r){const e=new yL(r),t=[],i=[];function n(){t.length=0,i.length=0}function s(h){t.push(h)}function a(h){i.push(h)}function o(h){e.setup(t,h)}function l(h){e.setupView(t,h)}return{init:n,state:{lightsArray:t,shadowsArray:i,lights:e,transmissionRenderTarget:null},setupLights:o,setupLightsView:l,pushLight:s,pushShadow:a}}function vL(r){let e=new WeakMap;function t(n,s=0){const a=e.get(n);let o;return a===void 0?(o=new pC(r),e.set(n,[o])):s>=a.length?(o=new pC(r),a.push(o)):o=a[s],o}function i(){e=new WeakMap}return{get:t,dispose:i}}class xc extends tn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=xA,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class sy extends tn{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const _L=`void main() {
	gl_Position = vec4( position, 1.0 );
}`,bL=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
void main() {
	const float samples = float( VSM_SAMPLES );
	float mean = 0.0;
	float squared_mean = 0.0;
	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
	for ( float i = 0.0; i < samples; i ++ ) {
		float uvOffset = uvStart + i * uvStride;
		#ifdef HORIZONTAL_PASS
			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;function wL(r,e,t){let i=new hu;const n=new $,s=new $,a=new rt,o=new xc({depthPacking:tc}),l=new sy,c={},h=t.maxTextureSize,u={[fs]:Rn,[Rn]:fs,[Zi]:Zi},d=new nn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new $},radius:{value:4}},vertexShader:_L,fragmentShader:bL}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const m=new $e;m.setAttribute("position",new Xe(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const A=new ye(m,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Kg;let y=this.type;this.render=function(E,M,S){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||E.length===0)return;const w=r.getRenderTarget(),C=r.getActiveCubeFace(),D=r.getActiveMipmapLevel(),O=r.state;O.setBlending(gn),O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);const F=y!==Yr&&this.type===Yr,G=y===Yr&&this.type!==Yr;for(let j=0,W=E.length;j<W;j++){const K=E[j],q=K.shadow;if(q===void 0){console.warn("THREE.WebGLShadowMap:",K,"has no shadow.");continue}if(q.autoUpdate===!1&&q.needsUpdate===!1)continue;n.copy(q.mapSize);const oe=q.getFrameExtents();if(n.multiply(oe),s.copy(q.mapSize),(n.x>h||n.y>h)&&(n.x>h&&(s.x=Math.floor(h/oe.x),n.x=s.x*oe.x,q.mapSize.x=s.x),n.y>h&&(s.y=Math.floor(h/oe.y),n.y=s.y*oe.y,q.mapSize.y=s.y)),q.map===null||F===!0||G===!0){const Ce=this.type!==Yr?{minFilter:pi,magFilter:pi}:{};q.map!==null&&q.map.dispose(),q.map=new ps(n.x,n.y,Ce),q.map.texture.name=K.name+".shadowMap",q.camera.updateProjectionMatrix()}r.setRenderTarget(q.map),r.clear();const re=q.getViewportCount();for(let Ce=0;Ce<re;Ce++){const Ie=q.getViewport(Ce);a.set(s.x*Ie.x,s.y*Ie.y,s.x*Ie.z,s.y*Ie.w),O.viewport(a),q.updateMatrices(K,Ce),i=q.getFrustum(),b(M,S,q.camera,K,this.type)}q.isPointLightShadow!==!0&&this.type===Yr&&_(q,S),q.needsUpdate=!1}y=this.type,g.needsUpdate=!1,r.setRenderTarget(w,C,D)};function _(E,M){const S=e.update(A);d.defines.VSM_SAMPLES!==E.blurSamples&&(d.defines.VSM_SAMPLES=E.blurSamples,p.defines.VSM_SAMPLES=E.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),E.mapPass===null&&(E.mapPass=new ps(n.x,n.y)),d.uniforms.shadow_pass.value=E.map.texture,d.uniforms.resolution.value=E.mapSize,d.uniforms.radius.value=E.radius,r.setRenderTarget(E.mapPass),r.clear(),r.renderBufferDirect(M,null,S,d,A,null),p.uniforms.shadow_pass.value=E.mapPass.texture,p.uniforms.resolution.value=E.mapSize,p.uniforms.radius.value=E.radius,r.setRenderTarget(E.map),r.clear(),r.renderBufferDirect(M,null,S,p,A,null)}function v(E,M,S,w){let C=null;const D=S.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(D!==void 0)C=D;else if(C=S.isPointLight===!0?l:o,r.localClippingEnabled&&M.clipShadows===!0&&Array.isArray(M.clippingPlanes)&&M.clippingPlanes.length!==0||M.displacementMap&&M.displacementScale!==0||M.alphaMap&&M.alphaTest>0||M.map&&M.alphaTest>0){const O=C.uuid,F=M.uuid;let G=c[O];G===void 0&&(G={},c[O]=G);let j=G[F];j===void 0&&(j=C.clone(),G[F]=j,M.addEventListener("dispose",T)),C=j}if(C.visible=M.visible,C.wireframe=M.wireframe,w===Yr?C.side=M.shadowSide!==null?M.shadowSide:M.side:C.side=M.shadowSide!==null?M.shadowSide:u[M.side],C.alphaMap=M.alphaMap,C.alphaTest=M.alphaTest,C.map=M.map,C.clipShadows=M.clipShadows,C.clippingPlanes=M.clippingPlanes,C.clipIntersection=M.clipIntersection,C.displacementMap=M.displacementMap,C.displacementScale=M.displacementScale,C.displacementBias=M.displacementBias,C.wireframeLinewidth=M.wireframeLinewidth,C.linewidth=M.linewidth,S.isPointLight===!0&&C.isMeshDistanceMaterial===!0){const O=r.properties.get(C);O.light=S}return C}function b(E,M,S,w,C){if(E.visible===!1)return;if(E.layers.test(M.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&C===Yr)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,E.matrixWorld);const F=e.update(E),G=E.material;if(Array.isArray(G)){const j=F.groups;for(let W=0,K=j.length;W<K;W++){const q=j[W],oe=G[q.materialIndex];if(oe&&oe.visible){const re=v(E,oe,w,C);E.onBeforeShadow(r,E,M,S,F,re,q),r.renderBufferDirect(S,null,F,re,E,q),E.onAfterShadow(r,E,M,S,F,re,q)}}}else if(G.visible){const j=v(E,G,w,C);E.onBeforeShadow(r,E,M,S,F,j,null),r.renderBufferDirect(S,null,F,j,E,null),E.onAfterShadow(r,E,M,S,F,j,null)}}const O=E.children;for(let F=0,G=O.length;F<G;F++)b(O[F],M,S,w,C)}function T(E){E.target.removeEventListener("dispose",T);for(const S in c){const w=c[S],C=E.target.uuid;C in w&&(w[C].dispose(),delete w[C])}}}function CL(r){function e(){let I=!1;const ie=new rt;let X=null;const Pe=new rt(0,0,0,0);return{setMask:function(Ve){X!==Ve&&!I&&(r.colorMask(Ve,Ve,Ve,Ve),X=Ve)},setLocked:function(Ve){I=Ve},setClear:function(Ve,jt,Ot,Si,hn){hn===!0&&(Ve*=Si,jt*=Si,Ot*=Si),ie.set(Ve,jt,Ot,Si),Pe.equals(ie)===!1&&(r.clearColor(Ve,jt,Ot,Si),Pe.copy(ie))},reset:function(){I=!1,X=null,Pe.set(-1,0,0,0)}}}function t(){let I=!1,ie=null,X=null,Pe=null;return{setTest:function(Ve){Ve?me(r.DEPTH_TEST):we(r.DEPTH_TEST)},setMask:function(Ve){ie!==Ve&&!I&&(r.depthMask(Ve),ie=Ve)},setFunc:function(Ve){if(X!==Ve){switch(Ve){case Sb:r.depthFunc(r.NEVER);break;case Eb:r.depthFunc(r.ALWAYS);break;case Mb:r.depthFunc(r.LESS);break;case ql:r.depthFunc(r.LEQUAL);break;case Tb:r.depthFunc(r.EQUAL);break;case Ib:r.depthFunc(r.GEQUAL);break;case Pb:r.depthFunc(r.GREATER);break;case Db:r.depthFunc(r.NOTEQUAL);break;default:r.depthFunc(r.LEQUAL)}X=Ve}},setLocked:function(Ve){I=Ve},setClear:function(Ve){Pe!==Ve&&(r.clearDepth(Ve),Pe=Ve)},reset:function(){I=!1,ie=null,X=null,Pe=null}}}function i(){let I=!1,ie=null,X=null,Pe=null,Ve=null,jt=null,Ot=null,Si=null,hn=null;return{setTest:function(ii){I||(ii?me(r.STENCIL_TEST):we(r.STENCIL_TEST))},setMask:function(ii){ie!==ii&&!I&&(r.stencilMask(ii),ie=ii)},setFunc:function(ii,es,Ji){(X!==ii||Pe!==es||Ve!==Ji)&&(r.stencilFunc(ii,es,Ji),X=ii,Pe=es,Ve=Ji)},setOp:function(ii,es,Ji){(jt!==ii||Ot!==es||Si!==Ji)&&(r.stencilOp(ii,es,Ji),jt=ii,Ot=es,Si=Ji)},setLocked:function(ii){I=ii},setClear:function(ii){hn!==ii&&(r.clearStencil(ii),hn=ii)},reset:function(){I=!1,ie=null,X=null,Pe=null,Ve=null,jt=null,Ot=null,Si=null,hn=null}}}const n=new e,s=new t,a=new i,o=new WeakMap,l=new WeakMap;let c={},h={},u=new WeakMap,d=[],p=null,m=!1,A=null,g=null,y=null,_=null,v=null,b=null,T=null,E=new se(0,0,0),M=0,S=!1,w=null,C=null,D=null,O=null,F=null;const G=r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let j=!1,W=0;const K=r.getParameter(r.VERSION);K.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(K)[1]),j=W>=1):K.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(K)[1]),j=W>=2);let q=null,oe={};const re=r.getParameter(r.SCISSOR_BOX),Ce=r.getParameter(r.VIEWPORT),Ie=new rt().fromArray(re),Ue=new rt().fromArray(Ce);function te(I,ie,X,Pe){const Ve=new Uint8Array(4),jt=r.createTexture();r.bindTexture(I,jt),r.texParameteri(I,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(I,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let Ot=0;Ot<X;Ot++)I===r.TEXTURE_3D||I===r.TEXTURE_2D_ARRAY?r.texImage3D(ie,0,r.RGBA,1,1,Pe,0,r.RGBA,r.UNSIGNED_BYTE,Ve):r.texImage2D(ie+Ot,0,r.RGBA,1,1,0,r.RGBA,r.UNSIGNED_BYTE,Ve);return jt}const ce={};ce[r.TEXTURE_2D]=te(r.TEXTURE_2D,r.TEXTURE_2D,1),ce[r.TEXTURE_CUBE_MAP]=te(r.TEXTURE_CUBE_MAP,r.TEXTURE_CUBE_MAP_POSITIVE_X,6),ce[r.TEXTURE_2D_ARRAY]=te(r.TEXTURE_2D_ARRAY,r.TEXTURE_2D_ARRAY,1,1),ce[r.TEXTURE_3D]=te(r.TEXTURE_3D,r.TEXTURE_3D,1,1),n.setClear(0,0,0,1),s.setClear(1),a.setClear(0),me(r.DEPTH_TEST),s.setFunc(ql),Ee(!1),De(vb),me(r.CULL_FACE),he(gn);function me(I){c[I]!==!0&&(r.enable(I),c[I]=!0)}function we(I){c[I]!==!1&&(r.disable(I),c[I]=!1)}function je(I,ie){return h[I]!==ie?(r.bindFramebuffer(I,ie),h[I]=ie,I===r.DRAW_FRAMEBUFFER&&(h[r.FRAMEBUFFER]=ie),I===r.FRAMEBUFFER&&(h[r.DRAW_FRAMEBUFFER]=ie),!0):!1}function ht(I,ie){let X=d,Pe=!1;if(I){X=u.get(ie),X===void 0&&(X=[],u.set(ie,X));const Ve=I.textures;if(X.length!==Ve.length||X[0]!==r.COLOR_ATTACHMENT0){for(let jt=0,Ot=Ve.length;jt<Ot;jt++)X[jt]=r.COLOR_ATTACHMENT0+jt;X.length=Ve.length,Pe=!0}}else X[0]!==r.BACK&&(X[0]=r.BACK,Pe=!0);Pe&&r.drawBuffers(X)}function Ze(I){return p!==I?(r.useProgram(I),p=I,!0):!1}const Y={[Sr]:r.FUNC_ADD,[_b]:r.FUNC_SUBTRACT,[bb]:r.FUNC_REVERSE_SUBTRACT};Y[wb]=r.MIN,Y[Cb]=r.MAX;const fe={[Jg]:r.ZERO,[Zg]:r.ONE,[eA]:r.SRC_COLOR,[Hl]:r.SRC_ALPHA,[xb]:r.SRC_ALPHA_SATURATE,[sA]:r.DST_COLOR,[iA]:r.DST_ALPHA,[tA]:r.ONE_MINUS_SRC_COLOR,[Ql]:r.ONE_MINUS_SRC_ALPHA,[rA]:r.ONE_MINUS_DST_COLOR,[nA]:r.ONE_MINUS_DST_ALPHA,[Yh]:r.CONSTANT_COLOR,[$h]:r.ONE_MINUS_CONSTANT_COLOR,[jl]:r.CONSTANT_ALPHA,[Wl]:r.ONE_MINUS_CONSTANT_ALPHA};function he(I,ie,X,Pe,Ve,jt,Ot,Si,hn,ii){if(I===gn){m===!0&&(we(r.BLEND),m=!1);return}if(m===!1&&(me(r.BLEND),m=!0),I!==ir){if(I!==A||ii!==S){if((g!==Sr||v!==Sr)&&(r.blendEquation(r.FUNC_ADD),g=Sr,v=Sr),ii)switch(I){case xr:r.blendFuncSeparate(r.ONE,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case rf:r.blendFunc(r.ONE,r.ONE);break;case af:r.blendFuncSeparate(r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case of:r.blendFuncSeparate(r.ZERO,r.SRC_COLOR,r.ZERO,r.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",I);break}else switch(I){case xr:r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case rf:r.blendFunc(r.SRC_ALPHA,r.ONE);break;case af:r.blendFuncSeparate(r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case of:r.blendFunc(r.ZERO,r.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",I);break}y=null,_=null,b=null,T=null,E.set(0,0,0),M=0,A=I,S=ii}return}Ve=Ve||ie,jt=jt||X,Ot=Ot||Pe,(ie!==g||Ve!==v)&&(r.blendEquationSeparate(Y[ie],Y[Ve]),g=ie,v=Ve),(X!==y||Pe!==_||jt!==b||Ot!==T)&&(r.blendFuncSeparate(fe[X],fe[Pe],fe[jt],fe[Ot]),y=X,_=Pe,b=jt,T=Ot),(Si.equals(E)===!1||hn!==M)&&(r.blendColor(Si.r,Si.g,Si.b,hn),E.copy(Si),M=hn),A=I,S=!1}function Se(I,ie){I.side===Zi?we(r.CULL_FACE):me(r.CULL_FACE);let X=I.side===Rn;ie&&(X=!X),Ee(X),I.blending===xr&&I.transparent===!1?he(gn):he(I.blending,I.blendEquation,I.blendSrc,I.blendDst,I.blendEquationAlpha,I.blendSrcAlpha,I.blendDstAlpha,I.blendColor,I.blendAlpha,I.premultipliedAlpha),s.setFunc(I.depthFunc),s.setTest(I.depthTest),s.setMask(I.depthWrite),n.setMask(I.colorWrite);const Pe=I.stencilWrite;a.setTest(Pe),Pe&&(a.setMask(I.stencilWriteMask),a.setFunc(I.stencilFunc,I.stencilRef,I.stencilFuncMask),a.setOp(I.stencilFail,I.stencilZFail,I.stencilZPass)),B(I.polygonOffset,I.polygonOffsetFactor,I.polygonOffsetUnits),I.alphaToCoverage===!0?me(r.SAMPLE_ALPHA_TO_COVERAGE):we(r.SAMPLE_ALPHA_TO_COVERAGE)}function Ee(I){w!==I&&(I?r.frontFace(r.CW):r.frontFace(r.CCW),w=I)}function De(I){I!==yP?(me(r.CULL_FACE),I!==C&&(I===vb?r.cullFace(r.BACK):I===vP?r.cullFace(r.FRONT):r.cullFace(r.FRONT_AND_BACK))):we(r.CULL_FACE),C=I}function N(I){I!==D&&(j&&r.lineWidth(I),D=I)}function B(I,ie,X){I?(me(r.POLYGON_OFFSET_FILL),(O!==ie||F!==X)&&(r.polygonOffset(ie,X),O=ie,F=X)):we(r.POLYGON_OFFSET_FILL)}function J(I){I?me(r.SCISSOR_TEST):we(r.SCISSOR_TEST)}function le(I){I===void 0&&(I=r.TEXTURE0+G-1),q!==I&&(r.activeTexture(I),q=I)}function ue(I,ie,X){X===void 0&&(q===null?X=r.TEXTURE0+G-1:X=q);let Pe=oe[X];Pe===void 0&&(Pe={type:void 0,texture:void 0},oe[X]=Pe),(Pe.type!==I||Pe.texture!==ie)&&(q!==X&&(r.activeTexture(X),q=X),r.bindTexture(I,ie||ce[I]),Pe.type=I,Pe.texture=ie)}function ve(){const I=oe[q];I!==void 0&&I.type!==void 0&&(r.bindTexture(I.type,null),I.type=void 0,I.texture=void 0)}function Ke(){try{r.compressedTexImage2D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function be(){try{r.compressedTexImage3D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Ye(){try{r.texSubImage2D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function at(){try{r.texSubImage3D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Be(){try{r.compressedTexSubImage2D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Ne(){try{r.compressedTexSubImage3D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function dt(){try{r.texStorage2D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function We(){try{r.texStorage3D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function qe(){try{r.texImage2D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function Ft(){try{r.texImage3D.apply(r,arguments)}catch(I){console.error("THREE.WebGLState:",I)}}function yt(I){Ie.equals(I)===!1&&(r.scissor(I.x,I.y,I.z,I.w),Ie.copy(I))}function Mt(I){Ue.equals(I)===!1&&(r.viewport(I.x,I.y,I.z,I.w),Ue.copy(I))}function Qt(I,ie){let X=l.get(ie);X===void 0&&(X=new WeakMap,l.set(ie,X));let Pe=X.get(I);Pe===void 0&&(Pe=r.getUniformBlockIndex(ie,I.name),X.set(I,Pe))}function Nt(I,ie){const Pe=l.get(ie).get(I);o.get(ie)!==Pe&&(r.uniformBlockBinding(ie,Pe,I.__bindingPointIndex),o.set(ie,Pe))}function ze(){r.disable(r.BLEND),r.disable(r.CULL_FACE),r.disable(r.DEPTH_TEST),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SCISSOR_TEST),r.disable(r.STENCIL_TEST),r.disable(r.SAMPLE_ALPHA_TO_COVERAGE),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ONE,r.ZERO),r.blendFuncSeparate(r.ONE,r.ZERO,r.ONE,r.ZERO),r.blendColor(0,0,0,0),r.colorMask(!0,!0,!0,!0),r.clearColor(0,0,0,0),r.depthMask(!0),r.depthFunc(r.LESS),r.clearDepth(1),r.stencilMask(4294967295),r.stencilFunc(r.ALWAYS,0,4294967295),r.stencilOp(r.KEEP,r.KEEP,r.KEEP),r.clearStencil(0),r.cullFace(r.BACK),r.frontFace(r.CCW),r.polygonOffset(0,0),r.activeTexture(r.TEXTURE0),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),r.bindFramebuffer(r.READ_FRAMEBUFFER,null),r.useProgram(null),r.lineWidth(1),r.scissor(0,0,r.canvas.width,r.canvas.height),r.viewport(0,0,r.canvas.width,r.canvas.height),c={},q=null,oe={},h={},u=new WeakMap,d=[],p=null,m=!1,A=null,g=null,y=null,_=null,v=null,b=null,T=null,E=new se(0,0,0),M=0,S=!1,w=null,C=null,D=null,O=null,F=null,Ie.set(0,0,r.canvas.width,r.canvas.height),Ue.set(0,0,r.canvas.width,r.canvas.height),n.reset(),s.reset(),a.reset()}return{buffers:{color:n,depth:s,stencil:a},enable:me,disable:we,bindFramebuffer:je,drawBuffers:ht,useProgram:Ze,setBlending:he,setMaterial:Se,setFlipSided:Ee,setCullFace:De,setLineWidth:N,setPolygonOffset:B,setScissorTest:J,activeTexture:le,bindTexture:ue,unbindTexture:ve,compressedTexImage2D:Ke,compressedTexImage3D:be,texImage2D:qe,texImage3D:Ft,updateUBOMapping:Qt,uniformBlockBinding:Nt,texStorage2D:dt,texStorage3D:We,texSubImage2D:Ye,texSubImage3D:at,compressedTexSubImage2D:Be,compressedTexSubImage3D:Ne,scissor:yt,viewport:Mt,reset:ze}}function xL(r,e,t,i,n,s,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new $,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(N,B){return p?new OffscreenCanvas(N,B):nu("canvas")}function A(N,B,J){let le=1;const ue=De(N);if((ue.width>J||ue.height>J)&&(le=J/Math.max(ue.width,ue.height)),le<1)if(typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&N instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&N instanceof ImageBitmap||typeof VideoFrame<"u"&&N instanceof VideoFrame){const ve=Math.floor(le*ue.width),Ke=Math.floor(le*ue.height);u===void 0&&(u=m(ve,Ke));const be=B?m(ve,Ke):u;return be.width=ve,be.height=Ke,be.getContext("2d").drawImage(N,0,0,ve,Ke),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ue.width+"x"+ue.height+") to ("+ve+"x"+Ke+")."),be}else return"data"in N&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ue.width+"x"+ue.height+")."),N;return N}function g(N){return N.generateMipmaps&&N.minFilter!==pi&&N.minFilter!==st}function y(N){r.generateMipmap(N)}function _(N,B,J,le,ue=!1){if(N!==null){if(r[N]!==void 0)return r[N];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+N+"'")}let ve=B;if(B===r.RED&&(J===r.FLOAT&&(ve=r.R32F),J===r.HALF_FLOAT&&(ve=r.R16F),J===r.UNSIGNED_BYTE&&(ve=r.R8)),B===r.RED_INTEGER&&(J===r.UNSIGNED_BYTE&&(ve=r.R8UI),J===r.UNSIGNED_SHORT&&(ve=r.R16UI),J===r.UNSIGNED_INT&&(ve=r.R32UI),J===r.BYTE&&(ve=r.R8I),J===r.SHORT&&(ve=r.R16I),J===r.INT&&(ve=r.R32I)),B===r.RG&&(J===r.FLOAT&&(ve=r.RG32F),J===r.HALF_FLOAT&&(ve=r.RG16F),J===r.UNSIGNED_BYTE&&(ve=r.RG8)),B===r.RG_INTEGER&&(J===r.UNSIGNED_BYTE&&(ve=r.RG8UI),J===r.UNSIGNED_SHORT&&(ve=r.RG16UI),J===r.UNSIGNED_INT&&(ve=r.RG32UI),J===r.BYTE&&(ve=r.RG8I),J===r.SHORT&&(ve=r.RG16I),J===r.INT&&(ve=r.RG32I)),B===r.RGB&&J===r.UNSIGNED_INT_5_9_9_9_REV&&(ve=r.RGB9_E5),B===r.RGBA){const Ke=ue?pf:Xt.getTransfer(le);J===r.FLOAT&&(ve=r.RGBA32F),J===r.HALF_FLOAT&&(ve=r.RGBA16F),J===r.UNSIGNED_BYTE&&(ve=Ke===bi?r.SRGB8_ALPHA8:r.RGBA8),J===r.UNSIGNED_SHORT_4_4_4_4&&(ve=r.RGBA4),J===r.UNSIGNED_SHORT_5_5_5_1&&(ve=r.RGB5_A1)}return(ve===r.R16F||ve===r.R32F||ve===r.RG16F||ve===r.RG32F||ve===r.RGBA16F||ve===r.RGBA32F)&&e.get("EXT_color_buffer_float"),ve}function v(N,B){return g(N)===!0||N.isFramebufferTexture&&N.minFilter!==pi&&N.minFilter!==st?Math.log2(Math.max(B.width,B.height))+1:N.mipmaps!==void 0&&N.mipmaps.length>0?N.mipmaps.length:N.isCompressedTexture&&Array.isArray(N.image)?B.mipmaps.length:1}function b(N){const B=N.target;B.removeEventListener("dispose",b),E(B),B.isVideoTexture&&h.delete(B)}function T(N){const B=N.target;B.removeEventListener("dispose",T),S(B)}function E(N){const B=i.get(N);if(B.__webglInit===void 0)return;const J=N.source,le=d.get(J);if(le){const ue=le[B.__cacheKey];ue.usedTimes--,ue.usedTimes===0&&M(N),Object.keys(le).length===0&&d.delete(J)}i.remove(N)}function M(N){const B=i.get(N);r.deleteTexture(B.__webglTexture);const J=N.source,le=d.get(J);delete le[B.__cacheKey],a.memory.textures--}function S(N){const B=i.get(N);if(N.depthTexture&&N.depthTexture.dispose(),N.isWebGLCubeRenderTarget)for(let le=0;le<6;le++){if(Array.isArray(B.__webglFramebuffer[le]))for(let ue=0;ue<B.__webglFramebuffer[le].length;ue++)r.deleteFramebuffer(B.__webglFramebuffer[le][ue]);else r.deleteFramebuffer(B.__webglFramebuffer[le]);B.__webglDepthbuffer&&r.deleteRenderbuffer(B.__webglDepthbuffer[le])}else{if(Array.isArray(B.__webglFramebuffer))for(let le=0;le<B.__webglFramebuffer.length;le++)r.deleteFramebuffer(B.__webglFramebuffer[le]);else r.deleteFramebuffer(B.__webglFramebuffer);if(B.__webglDepthbuffer&&r.deleteRenderbuffer(B.__webglDepthbuffer),B.__webglMultisampledFramebuffer&&r.deleteFramebuffer(B.__webglMultisampledFramebuffer),B.__webglColorRenderbuffer)for(let le=0;le<B.__webglColorRenderbuffer.length;le++)B.__webglColorRenderbuffer[le]&&r.deleteRenderbuffer(B.__webglColorRenderbuffer[le]);B.__webglDepthRenderbuffer&&r.deleteRenderbuffer(B.__webglDepthRenderbuffer)}const J=N.textures;for(let le=0,ue=J.length;le<ue;le++){const ve=i.get(J[le]);ve.__webglTexture&&(r.deleteTexture(ve.__webglTexture),a.memory.textures--),i.remove(J[le])}i.remove(N)}let w=0;function C(){w=0}function D(){const N=w;return N>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+N+" texture units while this GPU supports only "+n.maxTextures),w+=1,N}function O(N){const B=[];return B.push(N.wrapS),B.push(N.wrapT),B.push(N.wrapR||0),B.push(N.magFilter),B.push(N.minFilter),B.push(N.anisotropy),B.push(N.internalFormat),B.push(N.format),B.push(N.type),B.push(N.generateMipmaps),B.push(N.premultiplyAlpha),B.push(N.flipY),B.push(N.unpackAlignment),B.push(N.colorSpace),B.join()}function F(N,B){const J=i.get(N);if(N.isVideoTexture&&Se(N),N.isRenderTargetTexture===!1&&N.version>0&&J.__version!==N.version){const le=N.image;if(le===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(le.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Ie(J,N,B);return}}t.bindTexture(r.TEXTURE_2D,J.__webglTexture,r.TEXTURE0+B)}function G(N,B){const J=i.get(N);if(N.version>0&&J.__version!==N.version){Ie(J,N,B);return}t.bindTexture(r.TEXTURE_2D_ARRAY,J.__webglTexture,r.TEXTURE0+B)}function j(N,B){const J=i.get(N);if(N.version>0&&J.__version!==N.version){Ie(J,N,B);return}t.bindTexture(r.TEXTURE_3D,J.__webglTexture,r.TEXTURE0+B)}function W(N,B){const J=i.get(N);if(N.version>0&&J.__version!==N.version){Ue(J,N,B);return}t.bindTexture(r.TEXTURE_CUBE_MAP,J.__webglTexture,r.TEXTURE0+B)}const K={[Bn]:r.REPEAT,[ui]:r.CLAMP_TO_EDGE,[Zr]:r.MIRRORED_REPEAT},q={[pi]:r.NEAREST,[Jh]:r.NEAREST_MIPMAP_NEAREST,[Na]:r.NEAREST_MIPMAP_LINEAR,[st]:r.LINEAR,[Po]:r.LINEAR_MIPMAP_NEAREST,[Ln]:r.LINEAR_MIPMAP_LINEAR},oe={[BP]:r.NEVER,[kP]:r.ALWAYS,[LP]:r.LESS,[dw]:r.LEQUAL,[OP]:r.EQUAL,[NP]:r.GEQUAL,[UP]:r.GREATER,[FP]:r.NOTEQUAL};function re(N,B){if(B.type===zt&&e.has("OES_texture_float_linear")===!1&&(B.magFilter===st||B.magFilter===Po||B.magFilter===Na||B.magFilter===Ln||B.minFilter===st||B.minFilter===Po||B.minFilter===Na||B.minFilter===Ln)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(N,r.TEXTURE_WRAP_S,K[B.wrapS]),r.texParameteri(N,r.TEXTURE_WRAP_T,K[B.wrapT]),(N===r.TEXTURE_3D||N===r.TEXTURE_2D_ARRAY)&&r.texParameteri(N,r.TEXTURE_WRAP_R,K[B.wrapR]),r.texParameteri(N,r.TEXTURE_MAG_FILTER,q[B.magFilter]),r.texParameteri(N,r.TEXTURE_MIN_FILTER,q[B.minFilter]),B.compareFunction&&(r.texParameteri(N,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(N,r.TEXTURE_COMPARE_FUNC,oe[B.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(B.magFilter===pi||B.minFilter!==Na&&B.minFilter!==Ln||B.type===zt&&e.has("OES_texture_float_linear")===!1)return;if(B.anisotropy>1||i.get(B).__currentAnisotropy){const J=e.get("EXT_texture_filter_anisotropic");r.texParameterf(N,J.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(B.anisotropy,n.getMaxAnisotropy())),i.get(B).__currentAnisotropy=B.anisotropy}}}function Ce(N,B){let J=!1;N.__webglInit===void 0&&(N.__webglInit=!0,B.addEventListener("dispose",b));const le=B.source;let ue=d.get(le);ue===void 0&&(ue={},d.set(le,ue));const ve=O(B);if(ve!==N.__cacheKey){ue[ve]===void 0&&(ue[ve]={texture:r.createTexture(),usedTimes:0},a.memory.textures++,J=!0),ue[ve].usedTimes++;const Ke=ue[N.__cacheKey];Ke!==void 0&&(ue[N.__cacheKey].usedTimes--,Ke.usedTimes===0&&M(B)),N.__cacheKey=ve,N.__webglTexture=ue[ve].texture}return J}function Ie(N,B,J){let le=r.TEXTURE_2D;(B.isDataArrayTexture||B.isCompressedArrayTexture)&&(le=r.TEXTURE_2D_ARRAY),B.isData3DTexture&&(le=r.TEXTURE_3D);const ue=Ce(N,B),ve=B.source;t.bindTexture(le,N.__webglTexture,r.TEXTURE0+J);const Ke=i.get(ve);if(ve.version!==Ke.__version||ue===!0){t.activeTexture(r.TEXTURE0+J);const be=Xt.getPrimaries(Xt.workingColorSpace),Ye=B.colorSpace===si||B.colorSpace===Gs?null:Xt.getPrimaries(B.colorSpace),at=B.colorSpace===si||B.colorSpace===Gs||be===Ye?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,B.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,B.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,at);let Be=A(B.image,!1,n.maxTextureSize);Be=Ee(B,Be);const Ne=s.convert(B.format,B.colorSpace),dt=s.convert(B.type);let We=_(B.internalFormat,Ne,dt,B.colorSpace,B.isVideoTexture);re(le,B);let qe;const Ft=B.mipmaps,yt=B.isVideoTexture!==!0&&We!==mA,Mt=Ke.__version===void 0||ue===!0,Qt=ve.dataReady,Nt=v(B,Be);if(B.isDepthTexture)We=r.DEPTH_COMPONENT16,B.type===zt?We=r.DEPTH_COMPONENT32F:B.type===ea?We=r.DEPTH_COMPONENT24:B.type===$l&&(We=r.DEPTH24_STENCIL8),Mt&&(yt?t.texStorage2D(r.TEXTURE_2D,1,We,Be.width,Be.height):t.texImage2D(r.TEXTURE_2D,0,We,Be.width,Be.height,0,Ne,dt,null));else if(B.isDataTexture)if(Ft.length>0){yt&&Mt&&t.texStorage2D(r.TEXTURE_2D,Nt,We,Ft[0].width,Ft[0].height);for(let ze=0,I=Ft.length;ze<I;ze++)qe=Ft[ze],yt?Qt&&t.texSubImage2D(r.TEXTURE_2D,ze,0,0,qe.width,qe.height,Ne,dt,qe.data):t.texImage2D(r.TEXTURE_2D,ze,We,qe.width,qe.height,0,Ne,dt,qe.data);B.generateMipmaps=!1}else yt?(Mt&&t.texStorage2D(r.TEXTURE_2D,Nt,We,Be.width,Be.height),Qt&&t.texSubImage2D(r.TEXTURE_2D,0,0,0,Be.width,Be.height,Ne,dt,Be.data)):t.texImage2D(r.TEXTURE_2D,0,We,Be.width,Be.height,0,Ne,dt,Be.data);else if(B.isCompressedTexture)if(B.isCompressedArrayTexture){yt&&Mt&&t.texStorage3D(r.TEXTURE_2D_ARRAY,Nt,We,Ft[0].width,Ft[0].height,Be.depth);for(let ze=0,I=Ft.length;ze<I;ze++)qe=Ft[ze],B.format!==Kt?Ne!==null?yt?Qt&&t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,ze,0,0,0,qe.width,qe.height,Be.depth,Ne,qe.data,0,0):t.compressedTexImage3D(r.TEXTURE_2D_ARRAY,ze,We,qe.width,qe.height,Be.depth,0,qe.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):yt?Qt&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,ze,0,0,0,qe.width,qe.height,Be.depth,Ne,dt,qe.data):t.texImage3D(r.TEXTURE_2D_ARRAY,ze,We,qe.width,qe.height,Be.depth,0,Ne,dt,qe.data)}else{yt&&Mt&&t.texStorage2D(r.TEXTURE_2D,Nt,We,Ft[0].width,Ft[0].height);for(let ze=0,I=Ft.length;ze<I;ze++)qe=Ft[ze],B.format!==Kt?Ne!==null?yt?Qt&&t.compressedTexSubImage2D(r.TEXTURE_2D,ze,0,0,qe.width,qe.height,Ne,qe.data):t.compressedTexImage2D(r.TEXTURE_2D,ze,We,qe.width,qe.height,0,qe.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):yt?Qt&&t.texSubImage2D(r.TEXTURE_2D,ze,0,0,qe.width,qe.height,Ne,dt,qe.data):t.texImage2D(r.TEXTURE_2D,ze,We,qe.width,qe.height,0,Ne,dt,qe.data)}else if(B.isDataArrayTexture)yt?(Mt&&t.texStorage3D(r.TEXTURE_2D_ARRAY,Nt,We,Be.width,Be.height,Be.depth),Qt&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,Be.width,Be.height,Be.depth,Ne,dt,Be.data)):t.texImage3D(r.TEXTURE_2D_ARRAY,0,We,Be.width,Be.height,Be.depth,0,Ne,dt,Be.data);else if(B.isData3DTexture)yt?(Mt&&t.texStorage3D(r.TEXTURE_3D,Nt,We,Be.width,Be.height,Be.depth),Qt&&t.texSubImage3D(r.TEXTURE_3D,0,0,0,0,Be.width,Be.height,Be.depth,Ne,dt,Be.data)):t.texImage3D(r.TEXTURE_3D,0,We,Be.width,Be.height,Be.depth,0,Ne,dt,Be.data);else if(B.isFramebufferTexture){if(Mt)if(yt)t.texStorage2D(r.TEXTURE_2D,Nt,We,Be.width,Be.height);else{let ze=Be.width,I=Be.height;for(let ie=0;ie<Nt;ie++)t.texImage2D(r.TEXTURE_2D,ie,We,ze,I,0,Ne,dt,null),ze>>=1,I>>=1}}else if(Ft.length>0){if(yt&&Mt){const ze=De(Ft[0]);t.texStorage2D(r.TEXTURE_2D,Nt,We,ze.width,ze.height)}for(let ze=0,I=Ft.length;ze<I;ze++)qe=Ft[ze],yt?Qt&&t.texSubImage2D(r.TEXTURE_2D,ze,0,0,Ne,dt,qe):t.texImage2D(r.TEXTURE_2D,ze,We,Ne,dt,qe);B.generateMipmaps=!1}else if(yt){if(Mt){const ze=De(Be);t.texStorage2D(r.TEXTURE_2D,Nt,We,ze.width,ze.height)}Qt&&t.texSubImage2D(r.TEXTURE_2D,0,0,0,Ne,dt,Be)}else t.texImage2D(r.TEXTURE_2D,0,We,Ne,dt,Be);g(B)&&y(le),Ke.__version=ve.version,B.onUpdate&&B.onUpdate(B)}N.__version=B.version}function Ue(N,B,J){if(B.image.length!==6)return;const le=Ce(N,B),ue=B.source;t.bindTexture(r.TEXTURE_CUBE_MAP,N.__webglTexture,r.TEXTURE0+J);const ve=i.get(ue);if(ue.version!==ve.__version||le===!0){t.activeTexture(r.TEXTURE0+J);const Ke=Xt.getPrimaries(Xt.workingColorSpace),be=B.colorSpace===si||B.colorSpace===Gs?null:Xt.getPrimaries(B.colorSpace),Ye=B.colorSpace===si||B.colorSpace===Gs||Ke===be?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,B.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,B.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ye);const at=B.isCompressedTexture||B.image[0].isCompressedTexture,Be=B.image[0]&&B.image[0].isDataTexture,Ne=[];for(let I=0;I<6;I++)!at&&!Be?Ne[I]=A(B.image[I],!0,n.maxCubemapSize):Ne[I]=Be?B.image[I].image:B.image[I],Ne[I]=Ee(B,Ne[I]);const dt=Ne[0],We=s.convert(B.format,B.colorSpace),qe=s.convert(B.type),Ft=_(B.internalFormat,We,qe,B.colorSpace),yt=B.isVideoTexture!==!0,Mt=ve.__version===void 0||le===!0,Qt=ue.dataReady;let Nt=v(B,dt);re(r.TEXTURE_CUBE_MAP,B);let ze;if(at){yt&&Mt&&t.texStorage2D(r.TEXTURE_CUBE_MAP,Nt,Ft,dt.width,dt.height);for(let I=0;I<6;I++){ze=Ne[I].mipmaps;for(let ie=0;ie<ze.length;ie++){const X=ze[ie];B.format!==Kt?We!==null?yt?Qt&&t.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie,0,0,X.width,X.height,We,X.data):t.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie,Ft,X.width,X.height,0,X.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):yt?Qt&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie,0,0,X.width,X.height,We,qe,X.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie,Ft,X.width,X.height,0,We,qe,X.data)}}}else{if(ze=B.mipmaps,yt&&Mt){ze.length>0&&Nt++;const I=De(Ne[0]);t.texStorage2D(r.TEXTURE_CUBE_MAP,Nt,Ft,I.width,I.height)}for(let I=0;I<6;I++)if(Be){yt?Qt&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,0,0,0,Ne[I].width,Ne[I].height,We,qe,Ne[I].data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,0,Ft,Ne[I].width,Ne[I].height,0,We,qe,Ne[I].data);for(let ie=0;ie<ze.length;ie++){const Pe=ze[ie].image[I].image;yt?Qt&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie+1,0,0,Pe.width,Pe.height,We,qe,Pe.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie+1,Ft,Pe.width,Pe.height,0,We,qe,Pe.data)}}else{yt?Qt&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,0,0,0,We,qe,Ne[I]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,0,Ft,We,qe,Ne[I]);for(let ie=0;ie<ze.length;ie++){const X=ze[ie];yt?Qt&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie+1,0,0,We,qe,X.image[I]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+I,ie+1,Ft,We,qe,X.image[I])}}}g(B)&&y(r.TEXTURE_CUBE_MAP),ve.__version=ue.version,B.onUpdate&&B.onUpdate(B)}N.__version=B.version}function te(N,B,J,le,ue,ve){const Ke=s.convert(J.format,J.colorSpace),be=s.convert(J.type),Ye=_(J.internalFormat,Ke,be,J.colorSpace);if(!i.get(B).__hasExternalTextures){const Be=Math.max(1,B.width>>ve),Ne=Math.max(1,B.height>>ve);ue===r.TEXTURE_3D||ue===r.TEXTURE_2D_ARRAY?t.texImage3D(ue,ve,Ye,Be,Ne,B.depth,0,Ke,be,null):t.texImage2D(ue,ve,Ye,Be,Ne,0,Ke,be,null)}t.bindFramebuffer(r.FRAMEBUFFER,N),he(B)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,le,ue,i.get(J).__webglTexture,0,fe(B)):(ue===r.TEXTURE_2D||ue>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&ue<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,le,ue,i.get(J).__webglTexture,ve),t.bindFramebuffer(r.FRAMEBUFFER,null)}function ce(N,B,J){if(r.bindRenderbuffer(r.RENDERBUFFER,N),B.depthBuffer&&!B.stencilBuffer){let le=r.DEPTH_COMPONENT24;if(J||he(B)){const ue=B.depthTexture;ue&&ue.isDepthTexture&&(ue.type===zt?le=r.DEPTH_COMPONENT32F:ue.type===ea&&(le=r.DEPTH_COMPONENT24));const ve=fe(B);he(B)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,ve,le,B.width,B.height):r.renderbufferStorageMultisample(r.RENDERBUFFER,ve,le,B.width,B.height)}else r.renderbufferStorage(r.RENDERBUFFER,le,B.width,B.height);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,N)}else if(B.depthBuffer&&B.stencilBuffer){const le=fe(B);J&&he(B)===!1?r.renderbufferStorageMultisample(r.RENDERBUFFER,le,r.DEPTH24_STENCIL8,B.width,B.height):he(B)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,le,r.DEPTH24_STENCIL8,B.width,B.height):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,B.width,B.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,N)}else{const le=B.textures;for(let ue=0;ue<le.length;ue++){const ve=le[ue],Ke=s.convert(ve.format,ve.colorSpace),be=s.convert(ve.type),Ye=_(ve.internalFormat,Ke,be,ve.colorSpace),at=fe(B);J&&he(B)===!1?r.renderbufferStorageMultisample(r.RENDERBUFFER,at,Ye,B.width,B.height):he(B)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,at,Ye,B.width,B.height):r.renderbufferStorage(r.RENDERBUFFER,Ye,B.width,B.height)}}r.bindRenderbuffer(r.RENDERBUFFER,null)}function me(N,B){if(B&&B.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(r.FRAMEBUFFER,N),!(B.depthTexture&&B.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!i.get(B.depthTexture).__webglTexture||B.depthTexture.image.width!==B.width||B.depthTexture.image.height!==B.height)&&(B.depthTexture.image.width=B.width,B.depthTexture.image.height=B.height,B.depthTexture.needsUpdate=!0),F(B.depthTexture,0);const le=i.get(B.depthTexture).__webglTexture,ue=fe(B);if(B.depthTexture.format===Do)he(B)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,le,0,ue):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,le,0);else if(B.depthTexture.format===Zh)he(B)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,le,0,ue):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,le,0);else throw new Error("Unknown depthTexture format")}function we(N){const B=i.get(N),J=N.isWebGLCubeRenderTarget===!0;if(N.depthTexture&&!B.__autoAllocateDepthBuffer){if(J)throw new Error("target.depthTexture not supported in Cube render targets");me(B.__webglFramebuffer,N)}else if(J){B.__webglDepthbuffer=[];for(let le=0;le<6;le++)t.bindFramebuffer(r.FRAMEBUFFER,B.__webglFramebuffer[le]),B.__webglDepthbuffer[le]=r.createRenderbuffer(),ce(B.__webglDepthbuffer[le],N,!1)}else t.bindFramebuffer(r.FRAMEBUFFER,B.__webglFramebuffer),B.__webglDepthbuffer=r.createRenderbuffer(),ce(B.__webglDepthbuffer,N,!1);t.bindFramebuffer(r.FRAMEBUFFER,null)}function je(N,B,J){const le=i.get(N);B!==void 0&&te(le.__webglFramebuffer,N,N.texture,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,0),J!==void 0&&we(N)}function ht(N){const B=N.texture,J=i.get(N),le=i.get(B);N.addEventListener("dispose",T);const ue=N.textures,ve=N.isWebGLCubeRenderTarget===!0,Ke=ue.length>1;if(Ke||(le.__webglTexture===void 0&&(le.__webglTexture=r.createTexture()),le.__version=B.version,a.memory.textures++),ve){J.__webglFramebuffer=[];for(let be=0;be<6;be++)if(B.mipmaps&&B.mipmaps.length>0){J.__webglFramebuffer[be]=[];for(let Ye=0;Ye<B.mipmaps.length;Ye++)J.__webglFramebuffer[be][Ye]=r.createFramebuffer()}else J.__webglFramebuffer[be]=r.createFramebuffer()}else{if(B.mipmaps&&B.mipmaps.length>0){J.__webglFramebuffer=[];for(let be=0;be<B.mipmaps.length;be++)J.__webglFramebuffer[be]=r.createFramebuffer()}else J.__webglFramebuffer=r.createFramebuffer();if(Ke)for(let be=0,Ye=ue.length;be<Ye;be++){const at=i.get(ue[be]);at.__webglTexture===void 0&&(at.__webglTexture=r.createTexture(),a.memory.textures++)}if(N.samples>0&&he(N)===!1){J.__webglMultisampledFramebuffer=r.createFramebuffer(),J.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,J.__webglMultisampledFramebuffer);for(let be=0;be<ue.length;be++){const Ye=ue[be];J.__webglColorRenderbuffer[be]=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,J.__webglColorRenderbuffer[be]);const at=s.convert(Ye.format,Ye.colorSpace),Be=s.convert(Ye.type),Ne=_(Ye.internalFormat,at,Be,Ye.colorSpace,N.isXRRenderTarget===!0),dt=fe(N);r.renderbufferStorageMultisample(r.RENDERBUFFER,dt,Ne,N.width,N.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+be,r.RENDERBUFFER,J.__webglColorRenderbuffer[be])}r.bindRenderbuffer(r.RENDERBUFFER,null),N.depthBuffer&&(J.__webglDepthRenderbuffer=r.createRenderbuffer(),ce(J.__webglDepthRenderbuffer,N,!0)),t.bindFramebuffer(r.FRAMEBUFFER,null)}}if(ve){t.bindTexture(r.TEXTURE_CUBE_MAP,le.__webglTexture),re(r.TEXTURE_CUBE_MAP,B);for(let be=0;be<6;be++)if(B.mipmaps&&B.mipmaps.length>0)for(let Ye=0;Ye<B.mipmaps.length;Ye++)te(J.__webglFramebuffer[be][Ye],N,B,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+be,Ye);else te(J.__webglFramebuffer[be],N,B,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+be,0);g(B)&&y(r.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Ke){for(let be=0,Ye=ue.length;be<Ye;be++){const at=ue[be],Be=i.get(at);t.bindTexture(r.TEXTURE_2D,Be.__webglTexture),re(r.TEXTURE_2D,at),te(J.__webglFramebuffer,N,at,r.COLOR_ATTACHMENT0+be,r.TEXTURE_2D,0),g(at)&&y(r.TEXTURE_2D)}t.unbindTexture()}else{let be=r.TEXTURE_2D;if((N.isWebGL3DRenderTarget||N.isWebGLArrayRenderTarget)&&(be=N.isWebGL3DRenderTarget?r.TEXTURE_3D:r.TEXTURE_2D_ARRAY),t.bindTexture(be,le.__webglTexture),re(be,B),B.mipmaps&&B.mipmaps.length>0)for(let Ye=0;Ye<B.mipmaps.length;Ye++)te(J.__webglFramebuffer[Ye],N,B,r.COLOR_ATTACHMENT0,be,Ye);else te(J.__webglFramebuffer,N,B,r.COLOR_ATTACHMENT0,be,0);g(B)&&y(be),t.unbindTexture()}N.depthBuffer&&we(N)}function Ze(N){const B=N.isWebGLMultipleRenderTargets===!0&&Array.isArray(N.texture)?N.texture:N.textures||[N.texture],J=N.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;for(let le=0,ue=B.length;le<ue;le++){const ve=B[le],Ke=i.get(ve),be=Ke.__webglTexture;Ke.__version!==ve.version&&(t.bindTexture(J,be),re(J,ve),t.unbindTexture(),Ke.__version=ve.version),g(ve)&&(t.bindTexture(J,be),y(J),t.unbindTexture())}}function Y(N){if(N.samples>0&&he(N)===!1){const B=N.textures,J=N.width,le=N.height;let ue=r.COLOR_BUFFER_BIT;const ve=[],Ke=N.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,be=i.get(N),Ye=B.length>1;if(Ye)for(let at=0;at<B.length;at++)t.bindFramebuffer(r.FRAMEBUFFER,be.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+at,r.RENDERBUFFER,null),t.bindFramebuffer(r.FRAMEBUFFER,be.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+at,r.TEXTURE_2D,null,0);t.bindFramebuffer(r.READ_FRAMEBUFFER,be.__webglMultisampledFramebuffer),t.bindFramebuffer(r.DRAW_FRAMEBUFFER,be.__webglFramebuffer);for(let at=0;at<B.length;at++){ve.push(r.COLOR_ATTACHMENT0+at),N.depthBuffer&&ve.push(Ke);const Be=be.__ignoreDepthValues!==void 0?be.__ignoreDepthValues:!1;if(Be===!1&&(N.depthBuffer&&(ue|=r.DEPTH_BUFFER_BIT),N.stencilBuffer&&be.__isTransmissionRenderTarget!==!0&&(ue|=r.STENCIL_BUFFER_BIT)),Ye&&r.framebufferRenderbuffer(r.READ_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.RENDERBUFFER,be.__webglColorRenderbuffer[at]),Be===!0&&(r.invalidateFramebuffer(r.READ_FRAMEBUFFER,[Ke]),r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,[Ke])),Ye){const Ne=i.get(B[at]).__webglTexture;r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,Ne,0)}r.blitFramebuffer(0,0,J,le,0,0,J,le,ue,r.NEAREST),l&&r.invalidateFramebuffer(r.READ_FRAMEBUFFER,ve)}if(t.bindFramebuffer(r.READ_FRAMEBUFFER,null),t.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),Ye)for(let at=0;at<B.length;at++){t.bindFramebuffer(r.FRAMEBUFFER,be.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+at,r.RENDERBUFFER,be.__webglColorRenderbuffer[at]);const Be=i.get(B[at]).__webglTexture;t.bindFramebuffer(r.FRAMEBUFFER,be.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+at,r.TEXTURE_2D,Be,0)}t.bindFramebuffer(r.DRAW_FRAMEBUFFER,be.__webglMultisampledFramebuffer)}}function fe(N){return Math.min(n.maxSamples,N.samples)}function he(N){const B=i.get(N);return N.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&B.__useRenderToTexture!==!1}function Se(N){const B=a.render.frame;h.get(N)!==B&&(h.set(N,B),N.update())}function Ee(N,B){const J=N.colorSpace,le=N.format,ue=N.type;return N.isCompressedTexture===!0||N.isVideoTexture===!0||J!==Dt&&J!==si&&(Xt.getTransfer(J)===bi?(le!==Kt||ue!==Wt)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):J===Gs||console.error("THREE.WebGLTextures: Unsupported texture color space:",J)),B}function De(N){return typeof HTMLImageElement<"u"&&N instanceof HTMLImageElement?(c.width=N.naturalWidth||N.width,c.height=N.naturalHeight||N.height):typeof VideoFrame<"u"&&N instanceof VideoFrame?(c.width=N.displayWidth,c.height=N.displayHeight):(c.width=N.width,c.height=N.height),c}this.allocateTextureUnit=D,this.resetTextureUnits=C,this.setTexture2D=F,this.setTexture2DArray=G,this.setTexture3D=j,this.setTextureCube=W,this.rebindTextures=je,this.setupRenderTarget=ht,this.updateRenderTargetMipmap=Ze,this.updateMultisampleRenderTarget=Y,this.setupDepthRenderbuffer=we,this.setupFrameBufferTexture=te,this.useMultisampledRTT=he}function mC(r,e){function t(i,n=si){let s;const a=Xt.getTransfer(n);if(i===Wt)return r.UNSIGNED_BYTE;if(i===cA)return r.UNSIGNED_SHORT_4_4_4_4;if(i===hA)return r.UNSIGNED_SHORT_5_5_5_1;if(i===SP)return r.UNSIGNED_INT_5_9_9_9_REV;if(i===kb)return r.BYTE;if(i===Gb)return r.SHORT;if(i===oA)return r.UNSIGNED_SHORT;if(i===lA)return r.INT;if(i===ea)return r.UNSIGNED_INT;if(i===zt)return r.FLOAT;if(i===$t)return r.HALF_FLOAT;if(i===EP)return r.ALPHA;if(i===MP)return r.RGB;if(i===Kt)return r.RGBA;if(i===TP)return r.LUMINANCE;if(i===IP)return r.LUMINANCE_ALPHA;if(i===Do)return r.DEPTH_COMPONENT;if(i===Zh)return r.DEPTH_STENCIL;if(i===ka)return r.RED;if(i===zb)return r.RED_INTEGER;if(i===Kl)return r.RG;if(i===Vb)return r.RG_INTEGER;if(i===Hb)return r.RGBA_INTEGER;if(i===cf||i===uA||i===dA||i===hf)if(a===bi)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===cf)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===uA)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===dA)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===hf)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===cf)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===uA)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===dA)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===hf)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===fA||i===Qb||i===pA||i===jb)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===fA)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Qb)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===pA)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===jb)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===mA)return s=e.get("WEBGL_compressed_texture_etc1"),s!==null?s.COMPRESSED_RGB_ETC1_WEBGL:null;if(i===gA||i===AA)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===gA)return a===bi?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===AA)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===yA||i===Wb||i===qb||i===Xb||i===uf||i===Yb||i===$b||i===Kb||i===Jb||i===Zb||i===ew||i===tw||i===iw||i===nw)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===yA)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Wb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===qb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Xb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===uf)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Yb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===$b)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Kb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Jb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Zb)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===ew)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===tw)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===iw)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===nw)return a===bi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===df||i===sw||i===rw)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===df)return a===bi?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===sw)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===rw)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===PP||i===aw||i===ow||i===lw)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===df)return s.COMPRESSED_RED_RGTC1_EXT;if(i===aw)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===ow)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===lw)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===$l?r.UNSIGNED_INT_24_8:r[i]!==void 0?r[i]:null}return{convert:t}}class gC extends Vi{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Ri extends ft{constructor(){super(),this.isGroup=!0,this.type="Group"}}const SL={type:"move"};class ry{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Ri,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Ri,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new x,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new x),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Ri,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new x,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new x),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let n=null,s=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const A of e.hand.values()){const g=t.getJointPose(A,i),y=this._getHandJoint(c,A);g!==null&&(y.matrix.fromArray(g.transform.matrix),y.matrix.decompose(y.position,y.rotation,y.scale),y.matrixWorldNeedsUpdate=!0,y.jointRadius=g.radius),y.visible=g!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,m=.005;c.inputState.pinching&&d>p+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&s!==null&&(n=s),n!==null&&(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,this.dispatchEvent(SL)))}return o!==null&&(o.visible=n!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Ri;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const EL=`
void main() {

	gl_Position = vec4( position, 1.0 );

}`,ML=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;class TL{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,i){if(this.texture===null){const n=new Rt,s=e.properties.get(n);s.__webglTexture=t.texture,(t.depthNear!=i.depthNear||t.depthFar!=i.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}render(e,t){if(this.texture!==null){if(this.mesh===null){const i=t.cameras[0].viewport,n=new nn({vertexShader:EL,fragmentShader:ML,uniforms:{depthColor:{value:this.texture},depthWidth:{value:i.z},depthHeight:{value:i.w}}});this.mesh=new ye(new Er(20,20),n)}e.render(this.mesh,t)}}reset(){this.texture=null,this.mesh=null}}class IL extends wi{constructor(e,t){super();const i=this;let n=null,s=1,a=null,o="local-floor",l=1,c=null,h=null,u=null,d=null,p=null,m=null;const A=new TL,g=t.getContextAttributes();let y=null,_=null;const v=[],b=[],T=new $;let E=null;const M=new Vi;M.layers.enable(1),M.viewport=new rt;const S=new Vi;S.layers.enable(2),S.viewport=new rt;const w=[M,S],C=new gC;C.layers.enable(1),C.layers.enable(2);let D=null,O=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(te){let ce=v[te];return ce===void 0&&(ce=new ry,v[te]=ce),ce.getTargetRaySpace()},this.getControllerGrip=function(te){let ce=v[te];return ce===void 0&&(ce=new ry,v[te]=ce),ce.getGripSpace()},this.getHand=function(te){let ce=v[te];return ce===void 0&&(ce=new ry,v[te]=ce),ce.getHandSpace()};function F(te){const ce=b.indexOf(te.inputSource);if(ce===-1)return;const me=v[ce];me!==void 0&&(me.update(te.inputSource,te.frame,c||a),me.dispatchEvent({type:te.type,data:te.inputSource}))}function G(){n.removeEventListener("select",F),n.removeEventListener("selectstart",F),n.removeEventListener("selectend",F),n.removeEventListener("squeeze",F),n.removeEventListener("squeezestart",F),n.removeEventListener("squeezeend",F),n.removeEventListener("end",G),n.removeEventListener("inputsourceschange",j);for(let te=0;te<v.length;te++){const ce=b[te];ce!==null&&(b[te]=null,v[te].disconnect(ce))}D=null,O=null,A.reset(),e.setRenderTarget(y),p=null,d=null,u=null,n=null,_=null,Ue.stop(),i.isPresenting=!1,e.setPixelRatio(E),e.setSize(T.width,T.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(te){s=te,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(te){o=te,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(te){c=te},this.getBaseLayer=function(){return d!==null?d:p},this.getBinding=function(){return u},this.getFrame=function(){return m},this.getSession=function(){return n},this.setSession=async function(te){if(n=te,n!==null){if(y=e.getRenderTarget(),n.addEventListener("select",F),n.addEventListener("selectstart",F),n.addEventListener("selectend",F),n.addEventListener("squeeze",F),n.addEventListener("squeezestart",F),n.addEventListener("squeezeend",F),n.addEventListener("end",G),n.addEventListener("inputsourceschange",j),g.xrCompatible!==!0&&await t.makeXRCompatible(),E=e.getPixelRatio(),e.getSize(T),n.renderState.layers===void 0){const ce={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:s};p=new XRWebGLLayer(n,t,ce),n.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),_=new ps(p.framebufferWidth,p.framebufferHeight,{format:Kt,type:Wt,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil})}else{let ce=null,me=null,we=null;g.depth&&(we=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ce=g.stencil?Zh:Do,me=g.stencil?$l:ea);const je={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:s};u=new XRWebGLBinding(n,t),d=u.createProjectionLayer(je),n.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),_=new ps(d.textureWidth,d.textureHeight,{format:Kt,type:Wt,depthTexture:new jf(d.textureWidth,d.textureHeight,me,void 0,void 0,void 0,void 0,void 0,void 0,ce),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0});const ht=e.properties.get(_);ht.__ignoreDepthValues=d.ignoreDepthValues}_.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await n.requestReferenceSpace(o),Ue.setContext(n),Ue.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode};function j(te){for(let ce=0;ce<te.removed.length;ce++){const me=te.removed[ce],we=b.indexOf(me);we>=0&&(b[we]=null,v[we].disconnect(me))}for(let ce=0;ce<te.added.length;ce++){const me=te.added[ce];let we=b.indexOf(me);if(we===-1){for(let ht=0;ht<v.length;ht++)if(ht>=b.length){b.push(me),we=ht;break}else if(b[ht]===null){b[ht]=me,we=ht;break}if(we===-1)break}const je=v[we];je&&je.connect(me)}}const W=new x,K=new x;function q(te,ce,me){W.setFromMatrixPosition(ce.matrixWorld),K.setFromMatrixPosition(me.matrixWorld);const we=W.distanceTo(K),je=ce.projectionMatrix.elements,ht=me.projectionMatrix.elements,Ze=je[14]/(je[10]-1),Y=je[14]/(je[10]+1),fe=(je[9]+1)/je[5],he=(je[9]-1)/je[5],Se=(je[8]-1)/je[0],Ee=(ht[8]+1)/ht[0],De=Ze*Se,N=Ze*Ee,B=we/(-Se+Ee),J=B*-Se;ce.matrixWorld.decompose(te.position,te.quaternion,te.scale),te.translateX(J),te.translateZ(B),te.matrixWorld.compose(te.position,te.quaternion,te.scale),te.matrixWorldInverse.copy(te.matrixWorld).invert();const le=Ze+B,ue=Y+B,ve=De-J,Ke=N+(we-J),be=fe*Y/ue*le,Ye=he*Y/ue*le;te.projectionMatrix.makePerspective(ve,Ke,be,Ye,le,ue),te.projectionMatrixInverse.copy(te.projectionMatrix).invert()}function oe(te,ce){ce===null?te.matrixWorld.copy(te.matrix):te.matrixWorld.multiplyMatrices(ce.matrixWorld,te.matrix),te.matrixWorldInverse.copy(te.matrixWorld).invert()}this.updateCamera=function(te){if(n===null)return;A.texture!==null&&(te.near=A.depthNear,te.far=A.depthFar),C.near=S.near=M.near=te.near,C.far=S.far=M.far=te.far,(D!==C.near||O!==C.far)&&(n.updateRenderState({depthNear:C.near,depthFar:C.far}),D=C.near,O=C.far,M.near=D,M.far=O,S.near=D,S.far=O,M.updateProjectionMatrix(),S.updateProjectionMatrix(),te.updateProjectionMatrix());const ce=te.parent,me=C.cameras;oe(C,ce);for(let we=0;we<me.length;we++)oe(me[we],ce);me.length===2?q(C,M,S):C.projectionMatrix.copy(M.projectionMatrix),re(te,C,ce)};function re(te,ce,me){me===null?te.matrix.copy(ce.matrixWorld):(te.matrix.copy(me.matrixWorld),te.matrix.invert(),te.matrix.multiply(ce.matrixWorld)),te.matrix.decompose(te.position,te.quaternion,te.scale),te.updateMatrixWorld(!0),te.projectionMatrix.copy(ce.projectionMatrix),te.projectionMatrixInverse.copy(ce.projectionMatrixInverse),te.isPerspectiveCamera&&(te.fov=ic*2*Math.atan(1/te.projectionMatrix.elements[5]),te.zoom=1)}this.getCamera=function(){return C},this.getFoveation=function(){if(!(d===null&&p===null))return l},this.setFoveation=function(te){l=te,d!==null&&(d.fixedFoveation=te),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=te)},this.hasDepthSensing=function(){return A.texture!==null};let Ce=null;this.onPreAnimationFrameCallback=null;function Ie(te,ce){if(i.onPreAnimationFrameCallback&&i.onPreAnimationFrameCallback(te,ce),h=ce.getViewerPose(c||a),m=ce,h!==null){const me=h.views;p!==null&&(e.setRenderTargetFramebuffer(_,p.framebuffer),e.setRenderTarget(_));let we=!1;me.length!==C.cameras.length&&(C.cameras.length=0,we=!0);for(let ht=0;ht<me.length;ht++){const Ze=me[ht];let Y=null;if(p!==null)Y=p.getViewport(Ze);else{const he=u.getViewSubImage(d,Ze);Y=he.viewport,ht===0&&(e.setRenderTargetTextures(_,he.colorTexture,d.ignoreDepthValues?void 0:he.depthStencilTexture),e.setRenderTarget(_))}let fe=w[ht];fe===void 0&&(fe=new Vi,fe.layers.enable(ht),fe.viewport=new rt,w[ht]=fe),fe.matrix.fromArray(Ze.transform.matrix),fe.matrix.decompose(fe.position,fe.quaternion,fe.scale),fe.projectionMatrix.fromArray(Ze.projectionMatrix),fe.projectionMatrixInverse.copy(fe.projectionMatrix).invert(),fe.viewport.set(Y.x,Y.y,Y.width,Y.height),ht===0&&(C.matrix.copy(fe.matrix),C.matrix.decompose(C.position,C.quaternion,C.scale)),we===!0&&C.cameras.push(fe)}const je=n.enabledFeatures;if(je&&je.includes("depth-sensing")){const ht=u.getDepthInformation(me[0]);ht&&ht.isValid&&ht.texture&&A.init(e,ht,n.renderState)}}for(let me=0;me<v.length;me++){const we=b[me],je=v[me];we!==null&&je!==void 0&&je.update(we,ce,c||a)}A.render(e,C),Ce&&Ce(te,ce),ce.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ce}),m=null}const Ue=new zw;Ue.setAnimationLoop(Ie),this.setAnimationLoop=function(te){Ce=te},this.dispose=function(){}}}const Ho=new Tt,PL=new pe;function DL(r,e){function t(g,y){g.matrixAutoUpdate===!0&&g.updateMatrix(),y.value.copy(g.matrix)}function i(g,y){y.color.getRGB(g.fogColor.value,Fw(r)),y.isFog?(g.fogNear.value=y.near,g.fogFar.value=y.far):y.isFogExp2&&(g.fogDensity.value=y.density)}function n(g,y,_,v,b){y.isMeshBasicMaterial||y.isMeshLambertMaterial?s(g,y):y.isMeshToonMaterial?(s(g,y),u(g,y)):y.isMeshPhongMaterial?(s(g,y),h(g,y)):y.isMeshStandardMaterial?(s(g,y),d(g,y),y.isMeshPhysicalMaterial&&p(g,y,b)):y.isMeshMatcapMaterial?(s(g,y),m(g,y)):y.isMeshDepthMaterial?s(g,y):y.isMeshDistanceMaterial?(s(g,y),A(g,y)):y.isMeshNormalMaterial?s(g,y):y.isLineBasicMaterial?(a(g,y),y.isLineDashedMaterial&&o(g,y)):y.isPointsMaterial?l(g,y,_,v):y.isSpriteMaterial?c(g,y):y.isShadowMaterial?(g.color.value.copy(y.color),g.opacity.value=y.opacity):y.isShaderMaterial&&(y.transmission!==void 0&&(g.transmission&&(g.transmission.value=y.transmission),g.transmissionSamplerMap&&b&&(g.transmissionSamplerMap.value=b?b.texture:null),g.transmissionSamplerSize&&b&&g.transmissionSamplerSize.value.set(b.width,b.height)),y.uniformsNeedUpdate=!1)}function s(g,y){g.opacity.value=y.opacity,y.color&&g.diffuse.value.copy(y.color),y.emissive&&g.emissive.value.copy(y.emissive).multiplyScalar(y.emissiveIntensity),y.map&&(g.map.value=y.map,t(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,t(y.alphaMap,g.alphaMapTransform)),y.bumpMap&&(g.bumpMap.value=y.bumpMap,t(y.bumpMap,g.bumpMapTransform),g.bumpScale.value=y.bumpScale,y.side===Rn&&(g.bumpScale.value*=-1)),y.normalMap&&(g.normalMap.value=y.normalMap,t(y.normalMap,g.normalMapTransform),g.normalScale.value.copy(y.normalScale),y.side===Rn&&g.normalScale.value.negate()),y.displacementMap&&(g.displacementMap.value=y.displacementMap,t(y.displacementMap,g.displacementMapTransform),g.displacementScale.value=y.displacementScale,g.displacementBias.value=y.displacementBias),y.emissiveMap&&(g.emissiveMap.value=y.emissiveMap,t(y.emissiveMap,g.emissiveMapTransform)),y.specularMap&&(g.specularMap.value=y.specularMap,t(y.specularMap,g.specularMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest);const _=e.get(y),v=_.envMap,b=_.envMapRotation;if(v&&(g.envMap.value=v,Ho.copy(b),Ho.x*=-1,Ho.y*=-1,Ho.z*=-1,v.isCubeTexture&&v.isRenderTargetTexture===!1&&(Ho.y*=-1,Ho.z*=-1),g.envMapRotation.value.setFromMatrix4(PL.makeRotationFromEuler(Ho)),g.flipEnvMap.value=v.isCubeTexture&&v.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=y.reflectivity,g.ior.value=y.ior,g.refractionRatio.value=y.refractionRatio),y.lightMap){g.lightMap.value=y.lightMap;const T=r._useLegacyLights===!0?Math.PI:1;g.lightMapIntensity.value=y.lightMapIntensity*T,t(y.lightMap,g.lightMapTransform)}y.aoMap&&(g.aoMap.value=y.aoMap,g.aoMapIntensity.value=y.aoMapIntensity,t(y.aoMap,g.aoMapTransform))}function a(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,y.map&&(g.map.value=y.map,t(y.map,g.mapTransform))}function o(g,y){g.dashSize.value=y.dashSize,g.totalSize.value=y.dashSize+y.gapSize,g.scale.value=y.scale}function l(g,y,_,v){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.size.value=y.size*_,g.scale.value=v*.5,y.map&&(g.map.value=y.map,t(y.map,g.uvTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,t(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function c(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.rotation.value=y.rotation,y.map&&(g.map.value=y.map,t(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,t(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function h(g,y){g.specular.value.copy(y.specular),g.shininess.value=Math.max(y.shininess,1e-4)}function u(g,y){y.gradientMap&&(g.gradientMap.value=y.gradientMap)}function d(g,y){g.metalness.value=y.metalness,y.metalnessMap&&(g.metalnessMap.value=y.metalnessMap,t(y.metalnessMap,g.metalnessMapTransform)),g.roughness.value=y.roughness,y.roughnessMap&&(g.roughnessMap.value=y.roughnessMap,t(y.roughnessMap,g.roughnessMapTransform)),y.envMap&&(g.envMapIntensity.value=y.envMapIntensity)}function p(g,y,_){g.ior.value=y.ior,y.sheen>0&&(g.sheenColor.value.copy(y.sheenColor).multiplyScalar(y.sheen),g.sheenRoughness.value=y.sheenRoughness,y.sheenColorMap&&(g.sheenColorMap.value=y.sheenColorMap,t(y.sheenColorMap,g.sheenColorMapTransform)),y.sheenRoughnessMap&&(g.sheenRoughnessMap.value=y.sheenRoughnessMap,t(y.sheenRoughnessMap,g.sheenRoughnessMapTransform))),y.clearcoat>0&&(g.clearcoat.value=y.clearcoat,g.clearcoatRoughness.value=y.clearcoatRoughness,y.clearcoatMap&&(g.clearcoatMap.value=y.clearcoatMap,t(y.clearcoatMap,g.clearcoatMapTransform)),y.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=y.clearcoatRoughnessMap,t(y.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),y.clearcoatNormalMap&&(g.clearcoatNormalMap.value=y.clearcoatNormalMap,t(y.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(y.clearcoatNormalScale),y.side===Rn&&g.clearcoatNormalScale.value.negate())),y.iridescence>0&&(g.iridescence.value=y.iridescence,g.iridescenceIOR.value=y.iridescenceIOR,g.iridescenceThicknessMinimum.value=y.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=y.iridescenceThicknessRange[1],y.iridescenceMap&&(g.iridescenceMap.value=y.iridescenceMap,t(y.iridescenceMap,g.iridescenceMapTransform)),y.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=y.iridescenceThicknessMap,t(y.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),y.transmission>0&&(g.transmission.value=y.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),y.transmissionMap&&(g.transmissionMap.value=y.transmissionMap,t(y.transmissionMap,g.transmissionMapTransform)),g.thickness.value=y.thickness,y.thicknessMap&&(g.thicknessMap.value=y.thicknessMap,t(y.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=y.attenuationDistance,g.attenuationColor.value.copy(y.attenuationColor)),y.anisotropy>0&&(g.anisotropyVector.value.set(y.anisotropy*Math.cos(y.anisotropyRotation),y.anisotropy*Math.sin(y.anisotropyRotation)),y.anisotropyMap&&(g.anisotropyMap.value=y.anisotropyMap,t(y.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=y.specularIntensity,g.specularColor.value.copy(y.specularColor),y.specularColorMap&&(g.specularColorMap.value=y.specularColorMap,t(y.specularColorMap,g.specularColorMapTransform)),y.specularIntensityMap&&(g.specularIntensityMap.value=y.specularIntensityMap,t(y.specularIntensityMap,g.specularIntensityMapTransform))}function m(g,y){y.matcap&&(g.matcap.value=y.matcap)}function A(g,y){const _=e.get(y).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshTransformUniform:t,refreshFogUniforms:i,refreshMaterialUniforms:n}}function RL(r,e,t,i){let n={},s={},a=[];const o=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function l(_,v){const b=v.program;i.uniformBlockBinding(_,b)}function c(_,v){let b=n[_.id];b===void 0&&(m(_),b=h(_),n[_.id]=b,_.addEventListener("dispose",g));const T=v.program;i.updateUBOMapping(_,T);const E=e.render.frame;s[_.id]!==E&&(d(_),s[_.id]=E)}function h(_){const v=u();_.__bindingPointIndex=v;const b=r.createBuffer(),T=_.__size,E=_.usage;return r.bindBuffer(r.UNIFORM_BUFFER,b),r.bufferData(r.UNIFORM_BUFFER,T,E),r.bindBuffer(r.UNIFORM_BUFFER,null),r.bindBufferBase(r.UNIFORM_BUFFER,v,b),b}function u(){for(let _=0;_<o;_++)if(a.indexOf(_)===-1)return a.push(_),_;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(_){const v=n[_.id],b=_.uniforms,T=_.__cache;r.bindBuffer(r.UNIFORM_BUFFER,v);for(let E=0,M=b.length;E<M;E++){const S=Array.isArray(b[E])?b[E]:[b[E]];for(let w=0,C=S.length;w<C;w++){const D=S[w];if(p(D,E,w,T)===!0){const O=D.__offset,F=Array.isArray(D.value)?D.value:[D.value];let G=0;for(let j=0;j<F.length;j++){const W=F[j],K=A(W);typeof W=="number"||typeof W=="boolean"?(D.__data[0]=W,r.bufferSubData(r.UNIFORM_BUFFER,O+G,D.__data)):W.isMatrix3?(D.__data[0]=W.elements[0],D.__data[1]=W.elements[1],D.__data[2]=W.elements[2],D.__data[3]=0,D.__data[4]=W.elements[3],D.__data[5]=W.elements[4],D.__data[6]=W.elements[5],D.__data[7]=0,D.__data[8]=W.elements[6],D.__data[9]=W.elements[7],D.__data[10]=W.elements[8],D.__data[11]=0):(W.toArray(D.__data,G),G+=K.storage/Float32Array.BYTES_PER_ELEMENT)}r.bufferSubData(r.UNIFORM_BUFFER,O,D.__data)}}}r.bindBuffer(r.UNIFORM_BUFFER,null)}function p(_,v,b,T){const E=_.value,M=v+"_"+b;if(T[M]===void 0)return typeof E=="number"||typeof E=="boolean"?T[M]=E:T[M]=E.clone(),!0;{const S=T[M];if(typeof E=="number"||typeof E=="boolean"){if(S!==E)return T[M]=E,!0}else if(S.equals(E)===!1)return S.copy(E),!0}return!1}function m(_){const v=_.uniforms;let b=0;const T=16;for(let M=0,S=v.length;M<S;M++){const w=Array.isArray(v[M])?v[M]:[v[M]];for(let C=0,D=w.length;C<D;C++){const O=w[C],F=Array.isArray(O.value)?O.value:[O.value];for(let G=0,j=F.length;G<j;G++){const W=F[G],K=A(W),q=b%T;q!==0&&T-q<K.boundary&&(b+=T-q),O.__data=new Float32Array(K.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=b,b+=K.storage}}}const E=b%T;return E>0&&(b+=T-E),_.__size=b,_.__cache={},this}function A(_){const v={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(v.boundary=4,v.storage=4):_.isVector2?(v.boundary=8,v.storage=8):_.isVector3||_.isColor?(v.boundary=16,v.storage=12):_.isVector4?(v.boundary=16,v.storage=16):_.isMatrix3?(v.boundary=48,v.storage=48):_.isMatrix4?(v.boundary=64,v.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),v}function g(_){const v=_.target;v.removeEventListener("dispose",g);const b=a.indexOf(v.__bindingPointIndex);a.splice(b,1),r.deleteBuffer(n[v.id]),delete n[v.id],delete s[v.id]}function y(){for(const _ in n)r.deleteBuffer(n[_]);a=[],n={},s={}}return{bind:l,update:c,dispose:y}}class Xf{constructor(e={}){const{canvas:t=sD(),context:i=null,depth:n=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=e;this.isWebGLRenderer=!0;let d;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=i.getContextAttributes().alpha}else d=a;const p=new Uint32Array(4),m=new Int32Array(4);let A=null,g=null;const y=[],_=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=vt,this._useLegacyLights=!1,this.toneMapping=$r,this.toneMappingExposure=1,this.userData={},this.onContextLost=()=>{},this.onContextRestore=()=>{},this.onContextCreationError=()=>{};const v=this;let b=!1,T=0,E=0,M=null,S=-1,w=null;const C=new rt,D=new rt;let O=null;const F=new se(0);let G=0,j=t.width,W=t.height,K=1,q=null,oe=null;const re=new rt(0,0,j,W),Ce=new rt(0,0,j,W);let Ie=!1;const Ue=new hu;let te=!1,ce=!1;const me=new pe,we=new $,je=new x,ht={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function Ze(){return M===null?K:1}let Y=i;function fe(P,U){const k=t.getContext(P,U);return k!==null?k:null}try{const P={alpha:!0,depth:n,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine","three.js r163"),t.addEventListener("webglcontextlost",ie,!1),t.addEventListener("webglcontextrestored",X,!1),t.addEventListener("webglcontextcreationerror",Pe,!1),Y===null){const U="webgl2";if(Y=fe(U,P),Y===null)throw fe(U)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(P){throw console.error("THREE.WebGLRenderer: "+P.message),P}let he,Se,Ee,De,N,B,J,le,ue,ve,Ke,be,Ye,at,Be,Ne,dt,We,qe,Ft,yt,Mt,Qt,Nt;function ze(){he=new QB(Y),he.init(),Se=new NB(Y,he,e),Mt=new mC(Y,he),Ee=new CL(Y),De=new qB(Y),N=new uL,B=new xL(Y,he,Ee,N,Se,Mt,De),J=new GB(v),le=new HB(v),ue=new BD(Y),Qt=new UB(Y,ue),ve=new jB(Y,ue,De,Qt),Ke=new YB(Y,ve,ue,De),qe=new XB(Y,Se,B),Ne=new kB(N),be=new hL(v,J,le,he,Se,Qt,Ne),Ye=new DL(v,N),at=new fL,Be=new vL(he),We=new OB(v,J,le,Ee,Ke,d,l),dt=new wL(v,Ke,Se),Nt=new RL(Y,De,Se,Ee),Ft=new FB(Y,he,De),yt=new WB(Y,he,De),De.programs=be.programs,v.capabilities=Se,v.extensions=he,v.properties=N,v.renderLists=at,v.shadowMap=dt,v.state=Ee,v.info=De,v.background=We,v.cubemaps=J,v.cubeuvmaps=le,v.materials=Ye}ze();const I=new IL(v,Y);this.xr=I,this.getContext=function(){return Y},this.getContextAttributes=function(){return Y.getContextAttributes()},this.forceContextLoss=function(){const P=he.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=he.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return K},this.setPixelRatio=function(P){P!==void 0&&(K=P,this.setSize(j,W,!1))},this.getSize=function(P){return P.set(j,W)},this.setSize=function(P,U,k=!0){if(I.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}j=P,W=U,t.width=Math.floor(P*K),t.height=Math.floor(U*K),k===!0&&(t.style.width=P+"px",t.style.height=U+"px"),this.setViewport(0,0,P,U)},this.getDrawingBufferSize=function(P){return P.set(j*K,W*K).floor()},this.setDrawingBufferSize=function(P,U,k){j=P,W=U,K=k,t.width=Math.floor(P*k),t.height=Math.floor(U*k),this.setViewport(0,0,P,U)},this.getCurrentViewport=function(P){return P.copy(C)},this.getViewport=function(P){return P.copy(re)},this.setViewport=function(P,U,k,V){P.isVector4?re.set(P.x,P.y,P.z,P.w):re.set(P,U,k,V),Ee.viewport(C.copy(re).multiplyScalar(K).round())},this.getScissor=function(P){return P.copy(Ce)},this.setScissor=function(P,U,k,V){P.isVector4?Ce.set(P.x,P.y,P.z,P.w):Ce.set(P,U,k,V),Ee.scissor(D.copy(Ce).multiplyScalar(K).round())},this.getScissorTest=function(){return Ie},this.setScissorTest=function(P){Ee.setScissorTest(Ie=P)},this.setOpaqueSort=function(P){q=P},this.setTransparentSort=function(P){oe=P},this.getClearColor=function(P){return P.copy(We.getClearColor())},this.setClearColor=function(){We.setClearColor.apply(We,arguments)},this.getClearAlpha=function(){return We.getClearAlpha()},this.setClearAlpha=function(){We.setClearAlpha.apply(We,arguments)},this.clear=function(P=!0,U=!0,k=!0){let V=0;if(P){let H=!1;if(M!==null){const ee=M.texture.format;H=ee===Hb||ee===Vb||ee===zb}if(H){const ee=M.texture.type,ne=ee===Wt||ee===ea||ee===oA||ee===$l||ee===cA||ee===hA,Z=We.getClearColor(),ge=We.getClearAlpha(),Ae=Z.r,xe=Z.g,Te=Z.b;ne?(p[0]=Ae,p[1]=xe,p[2]=Te,p[3]=ge,Y.clearBufferuiv(Y.COLOR,0,p)):(m[0]=Ae,m[1]=xe,m[2]=Te,m[3]=ge,Y.clearBufferiv(Y.COLOR,0,m))}else V|=Y.COLOR_BUFFER_BIT}U&&(V|=Y.DEPTH_BUFFER_BIT),k&&(V|=Y.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Y.clear(V)},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(){t.removeEventListener("webglcontextlost",ie,!1),t.removeEventListener("webglcontextrestored",X,!1),t.removeEventListener("webglcontextcreationerror",Pe,!1),at.dispose(),Be.dispose(),N.dispose(),J.dispose(),le.dispose(),Ke.dispose(),Qt.dispose(),Nt.dispose(),be.dispose(),I.dispose(),I.removeEventListener("sessionstart",es),I.removeEventListener("sessionend",Ji),wn.stop()};function ie(P){P.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),b=!0,v.onContextLost(P)}function X(){console.log("THREE.WebGLRenderer: Context Restored."),b=!1;const P=v.info?v.info.autoReset:void 0,U=dt.enabled,k=dt.autoUpdate,V=dt.needsUpdate,H=dt.type;ze(),v.info&&P!==void 0&&(v.info.autoReset=P),dt.enabled=U,dt.autoUpdate=k,dt.needsUpdate=V,dt.type=H,v.onContextRestore&&v.onContextRestore()}function Pe(P){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage),v.onContextCreationError(P)}function Ve(P){const U=P.target;U.removeEventListener("dispose",Ve),jt(U)}function jt(P){Ot(P),N.remove(P)}function Ot(P){const U=N.get(P).programs;U!==void 0&&(U.forEach(function(k){be.releaseProgram(k)}),P.isShaderMaterial&&be.releaseShaderCache(P))}this.renderBufferDirect=function(P,U,k,V,H,ee){U===null&&(U=ht);const ne=H.isMesh&&H.matrixWorld.determinant()<0,Z=R(P,U,k,V,H);Ee.setMaterial(V,ne);let ge=k.index,Ae=1;if(V.wireframe===!0){if(ge=ve.getWireframeAttribute(k),ge===void 0)return;Ae=2}const xe=k.drawRange,Te=k.attributes.position;let Le=xe.start*Ae,He=(xe.start+xe.count)*Ae;ee!==null&&(Le=Math.max(Le,ee.start*Ae),He=Math.min(He,(ee.start+ee.count)*Ae)),ge!==null?(Le=Math.max(Le,0),He=Math.min(He,ge.count)):Te!=null&&(Le=Math.max(Le,0),He=Math.min(He,Te.count));const nt=He-Le;if(nt<0||nt===1/0)return;Qt.setup(H,V,Z,k,ge);let ni,_t=Ft;if(ge!==null&&(ni=ue.get(ge),_t=yt,_t.setIndex(ni)),H.isMesh)V.wireframe===!0?(Ee.setLineWidth(V.wireframeLinewidth*Ze()),_t.setMode(Y.LINES)):_t.setMode(Y.TRIANGLES);else if(H.isLine){let ut=V.linewidth;ut===void 0&&(ut=1),Ee.setLineWidth(ut*Ze()),H.isLineSegments?_t.setMode(Y.LINES):H.isLineLoop?_t.setMode(Y.LINE_LOOP):_t.setMode(Y.LINE_STRIP)}else H.isPoints?_t.setMode(Y.POINTS):H.isSprite&&_t.setMode(Y.TRIANGLES);if(H.isBatchedMesh)_t.renderMultiDraw(H._multiDrawStarts,H._multiDrawCounts,H._multiDrawCount);else if(H.isInstancedMesh)_t.renderInstances(Le,nt,H.count);else if(k.isInstancedBufferGeometry){const ut=k._maxInstanceCount!==void 0?k._maxInstanceCount:1/0,hi=Math.min(k.instanceCount,ut);_t.renderInstances(Le,nt,hi)}else _t.render(Le,nt)};function Si(P,U,k){P.transparent===!0&&P.side===Zi&&P.forceSinglePass===!1?(P.side=Rn,P.needsUpdate=!0,ts(P,U,k),P.side=fs,P.needsUpdate=!0,ts(P,U,k),P.side=Zi):ts(P,U,k)}this.compile=function(P,U,k=null){k===null&&(k=P),g=Be.get(k),g.init(),_.push(g),k.traverseVisible(function(H){H.isLight&&H.layers.test(U.layers)&&(g.pushLight(H),H.castShadow&&g.pushShadow(H))}),P!==k&&P.traverseVisible(function(H){H.isLight&&H.layers.test(U.layers)&&(g.pushLight(H),H.castShadow&&g.pushShadow(H))}),g.setupLights(v._useLegacyLights);const V=new Set;return P.traverse(function(H){const ee=H.material;if(ee)if(Array.isArray(ee))for(let ne=0;ne<ee.length;ne++){const Z=ee[ne];Si(Z,k,H),V.add(Z)}else Si(ee,k,H),V.add(ee)}),_.pop(),g=null,V},this.compileAsync=function(P,U,k=null){const V=this.compile(P,U,k);return new Promise(H=>{function ee(){if(V.forEach(function(ne){N.get(ne).currentProgram.isReady()&&V.delete(ne)}),V.size===0){H(P);return}setTimeout(ee,10)}he.get("KHR_parallel_shader_compile")!==null?ee():setTimeout(ee,10)})};let hn=null;function ii(P){hn&&hn(P)}function es(){wn.stop()}function Ji(){wn.start()}const wn=new zw;wn.setAnimationLoop(ii),typeof self<"u"&&wn.setContext(self),this.setAnimationLoop=function(P){hn=P,I.setAnimationLoop(P),P===null?wn.stop():wn.start()},I.addEventListener("sessionstart",es),I.addEventListener("sessionend",Ji),this.render=function(P,U){if(U!==void 0&&U.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(b!==!0){if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),U.parent===null&&U.matrixWorldAutoUpdate===!0&&U.updateMatrixWorld(),I.enabled===!0&&I.isPresenting===!0&&(I.cameraAutoUpdate===!0&&I.updateCamera(U),U=I.getCamera()),P.isScene===!0&&P.onBeforeRender(v,P,U,M),g=Be.get(P,_.length),g.init(),_.push(g),me.multiplyMatrices(U.projectionMatrix,U.matrixWorldInverse),Ue.setFromProjectionMatrix(me),ce=this.localClippingEnabled,te=Ne.init(this.clippingPlanes,ce),A=at.get(P,y.length),A.init(),y.push(A),To(P,U,0,v.sortObjects),A.finish(),v.sortObjects===!0&&A.sort(q,oe),this.info.render.frame++,v.userData.shadowMapRender!==!1){te===!0&&Ne.beginShadows();const k=g.state.shadowsArray;k.length>0&&dt.render(k,P,U),te===!0&&Ne.endShadows()}if(this.info.autoReset===!0&&this.info.reset(),v.userData.backgroundRender!==!1&&(I.enabled===!1||I.isPresenting===!1||I.hasDepthSensing()===!1)&&We.render(A,P),v.userData.sceneRender!==!1)if(g.setupLights(v._useLegacyLights),U.isArrayCamera){const k=U.cameras;for(let V=0,H=k.length;V<H;V++){const ee=k[V];Xr(A,P,ee,ee.viewport)}}else Xr(A,P,U);M!==null&&(B.updateMultisampleRenderTarget(M),B.updateRenderTargetMipmap(M)),P.isScene===!0&&P.onAfterRender(v,P,U),Qt.resetDefaultState(),S=-1,w=null,_.pop(),_.length>0?g=_[_.length-1]:g=null,y.pop(),y.length>0?A=y[y.length-1]:A=null}};function To(P,U,k,V){if(P.visible===!1)return;if(P.layers.test(U.layers)){if(P.isGroup)k=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(U);else if(P.isLight)g.pushLight(P),P.castShadow&&g.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||Ue.intersectsSprite(P)){V&&je.setFromMatrixPosition(P.matrixWorld).applyMatrix4(me);const ne=Ke.update(P),Z=P.material;Z.visible&&A.push(P,ne,Z,k,je.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||Ue.intersectsObject(P))){const ne=Ke.update(P),Z=P.material;if(V&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),je.copy(P.boundingSphere.center)):(ne.boundingSphere===null&&ne.computeBoundingSphere(),je.copy(ne.boundingSphere.center)),je.applyMatrix4(P.matrixWorld).applyMatrix4(me)),Array.isArray(Z)){const ge=ne.groups;for(let Ae=0,xe=ge.length;Ae<xe;Ae++){const Te=ge[Ae],Le=Z[Te.materialIndex];Le&&Le.visible&&A.push(P,ne,Le,k,je.z,Te)}}else Z.visible&&A.push(P,ne,Z,k,je.z,null)}}const ee=P.children;for(let ne=0,Z=ee.length;ne<Z;ne++)To(ee[ne],U,k,V)}function Xr(P,U,k,V){const H=P.opaque,ee=P.transmissive,ne=P.transparent;if(g.setupLightsView(k),te===!0&&Ne.setGlobalState(v.clippingPlanes,k),v.userData.transmissionRender===void 0&&v.userData.renderTransmissionPass!==!1&&ee.length>0&&Ua([...H,...ne],ee,U,k),V&&Ee.viewport(C.copy(V)),v.userData.opaqueRender!==!1&&H.length>0&&Cn(H,U,k),v.userData.transparentRender!==!1&&ne.length>0&&Cn(ne,U,k),v.userData.transmissionRender!==!1&&ee.length>0){g.state.transmissionRenderTarget||(g.state.transmissionRenderTarget=new ps(1,1));const Z=(v.userData.transmissionRenderTarget||g.state.transmissionRenderTarget).texture,ge=Se.isWebGL2,Ae=Z.generateMipmaps,xe=Z.minFilter;ge&&v.userData.blurTransmissionTarget&&v.userData.transmissionRenderTarget&&(Z.generateMipmaps=!0,Z.minFilter=Ln,Z.needsUpdate=!0,B.updateMultisampleRenderTarget(v.userData.transmissionRenderTarget),B.updateRenderTargetMipmap(v.userData.transmissionRenderTarget)),Cn(ee,U,k),ge&&v.userData.blurTransmissionTarget&&v.userData.transmissionRenderTarget&&(Z.generateMipmaps=Ae,Z.minFilter=xe,Z.needsUpdate=!0,B.updateMultisampleRenderTarget(v.userData.transmissionRenderTarget),B.updateRenderTargetMipmap(v.userData.transmissionRenderTarget))}Ee.buffers.depth.setTest(!0),Ee.buffers.depth.setMask(!0),Ee.buffers.color.setMask(!0),Ee.setPolygonOffset(!1)}function Ua(P,U,k,V){if(console.warn("three.js internal render transmission pass should not be called"),(k.isScene===!0?k.overrideMaterial:null)!==null)return;if(g.state.transmissionRenderTarget===null){g.state.transmissionRenderTarget=new ps(1,1,{generateMipmaps:!0,type:he.has("EXT_color_buffer_half_float")||he.has("EXT_color_buffer_float")?$t:Wt,minFilter:Ln,samples:4,stencilBuffer:s});const Ae=N.get(g.state.transmissionRenderTarget);Ae.__isTransmissionRenderTarget=!0}const ee=g.state.transmissionRenderTarget;v.getDrawingBufferSize(we),ee.setSize(we.x,we.y);const ne=v.getRenderTarget();v.setRenderTarget(ee),v.getClearColor(F),G=v.getClearAlpha(),G<1&&v.setClearColor(16777215,.5),v.clear();const Z=v.toneMapping;v.toneMapping=$r,Cn(P,k,V),B.updateMultisampleRenderTarget(ee),B.updateRenderTargetMipmap(ee);let ge=!1;for(let Ae=0,xe=U.length;Ae<xe;Ae++){const Te=U[Ae],Le=Te.object,He=Te.geometry,nt=Te.material,ni=Te.group;if(nt.side===Zi&&Le.layers.test(V.layers)){const _t=nt.side;nt.side=Rn,nt.needsUpdate=!0,Cs(Le,k,V,He,nt,ni),nt.side=_t,nt.needsUpdate=!0,ge=!0}}ge===!0&&(B.updateMultisampleRenderTarget(ee),B.updateRenderTargetMipmap(ee)),v.setRenderTarget(ne),v.setClearColor(F,G),v.toneMapping=Z}function Cn(P,U,k){const V={...v.userData};v.userData.opaqueRender=void 0,v.userData.transparentRender=void 0,v.userData.transmissionRender=void 0,v.userData.backgroundRender=void 0;const H=U.isScene===!0?U.overrideMaterial:null;for(let ee=0,ne=P.length;ee<ne;ee++){const Z=P[ee],ge=Z.object,Ae=Z.geometry,xe=Z.group;let Te=Z.material;Te.allowOverride===!0&&H!==null&&(Te=H),ge.layers.test(k.layers)&&Cs(ge,U,k,Ae,Te,xe)}Object.assign(v.userData,V)}function Cs(P,U,k,V,H,ee){P.onBeforeRender(v,U,k,V,H,ee),P.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,P.matrixWorld),P.normalMatrix.getNormalMatrix(P.modelViewMatrix),H.onBeforeRender(v,U,k,V,P,ee),H.transparent===!0&&H.side===Zi&&H.forceSinglePass===!1?(H.side=Rn,H.needsUpdate=!0,v.renderBufferDirect(k,U,V,H,P,ee),H.side=fs,H.needsUpdate=!0,v.renderBufferDirect(k,U,V,H,P,ee),H.side=Zi):v.renderBufferDirect(k,U,V,H,P,ee),P.onAfterRender(v,U,k,V,H,ee),H.onAfterRender(v,U,k,V,P,ee)}function ts(P,U,k){U.isScene!==!0&&(U=ht);const V=N.get(P),H=g.state.lights,ee=g.state.shadowsArray,ne=H.state.version,Z=be.getParameters(P,H.state,ee,U,k),ge=be.getProgramCacheKey(Z);let Ae=V.programs;V.environment=P.userData&&P.userData.envMapSlotKey&&U.textureSlots&&U.textureSlots[P.userData.envMapSlotKey]?U.textureSlots[P.userData.envMapSlotKey]:P.isMeshStandardMaterial?U.environment:null,V.fog=U.fog,V.envMap=(P.isMeshStandardMaterial?le:J).get(P.envMap||V.environment),V.envMapRotation=V.environment!==null&&P.envMap===null?U.environmentRotation:P.envMapRotation,Ae===void 0&&(P.addEventListener("dispose",Ve),Ae=new Map,V.programs=Ae);let xe=Ae.get(ge);if(xe!==void 0){if(V.currentProgram===xe&&V.lightsStateVersion===ne)return nf(P,Z),xe}else Z.uniforms=be.getUniforms(P),P.onBuild(k,Z,v),P.onBeforeCompile(Z,v),xe=be.acquireProgram(Z,ge),Ae.set(ge,xe),V.uniforms=Z.uniforms;const Te=V.uniforms;return(!P.isShaderMaterial&&!P.isRawShaderMaterial||P.clipping===!0)&&(Te.clippingPlanes=Ne.uniform),nf(P,Z),V.needsLights=Q(P),V.lightsStateVersion=ne,V.needsLights&&(Te.ambientLightColor.value=H.state.ambient,Te.lightProbe.value=H.state.probe,Te.directionalLights.value=H.state.directional,Te.directionalLightShadows.value=H.state.directionalShadow,Te.spotLights.value=H.state.spot,Te.spotLightShadows.value=H.state.spotShadow,Te.rectAreaLights.value=H.state.rectArea,Te.ltc_1.value=H.state.rectAreaLTC1,Te.ltc_2.value=H.state.rectAreaLTC2,Te.pointLights.value=H.state.point,Te.pointLightShadows.value=H.state.pointShadow,Te.hemisphereLights.value=H.state.hemi,Te.directionalShadowMap.value=H.state.directionalShadowMap,Te.directionalShadowMatrix.value=H.state.directionalShadowMatrix,Te.spotShadowMap.value=H.state.spotShadowMap,Te.spotLightMatrix.value=H.state.spotLightMatrix,Te.spotLightMap.value=H.state.spotLightMap,Te.pointShadowMap.value=H.state.pointShadowMap,Te.pointShadowMatrix.value=H.state.pointShadowMatrix),V.currentProgram=xe,V.uniformsList=null,xe}function Pt(P){if(P.uniformsList===null){const U=P.currentProgram.getUniforms();P.uniformsList=qf.seqWithValue(U.seq,P.uniforms)}return P.uniformsList}function nf(P,U){const k=N.get(P);k.outputColorSpace=U.outputColorSpace,k.batching=U.batching,k.instancing=U.instancing,k.instancingColor=U.instancingColor,k.instancingMorph=U.instancingMorph,k.skinning=U.skinning,k.morphTargets=U.morphTargets,k.morphNormals=U.morphNormals,k.morphColors=U.morphColors,k.morphTargetsCount=U.morphTargetsCount,k.numClippingPlanes=U.numClippingPlanes,k.numIntersection=U.numClipIntersection,k.vertexAlphas=U.vertexAlphas,k.vertexTangents=U.vertexTangents,k.toneMapping=U.toneMapping}function R(P,U,k,V,H){U.isScene!==!0&&(U=ht),B.resetTextureUnits();const ee=U.fog,ne=V.userData&&V.userData.envMapSlotKey&&U.textureSlots&&U.textureSlots[V.userData.envMapSlotKey]?U.textureSlots[V.userData.envMapSlotKey]:V.isMeshStandardMaterial?U.environment:null,Z=M===null?v.outputColorSpace:M.isXRRenderTarget===!0||M.texture.colorSpace&&M.texture.colorSpace!==vt?M.texture.colorSpace:Dt,ge=(V.isMeshStandardMaterial?le:J).get(V.envMap||ne),Ae=V.vertexColors===!0&&!!k.attributes.color&&k.attributes.color.itemSize===4,xe=!!k.attributes.tangent&&(!!V.normalMap||V.anisotropy>0||k.userData.__forceUseTangent),Te=!!k.morphAttributes.position,Le=!!k.morphAttributes.normal,He=!!k.morphAttributes.color;let nt=$r;V.toneMapped&&(M===null||M.isXRRenderTarget===!0)&&(nt=v.toneMapping);const ni=k.morphAttributes.position||k.morphAttributes.normal||k.morphAttributes.color,_t=ni!==void 0?ni.length:0,ut=N.get(V),hi=g.state.lights;if(te===!0&&(ce===!0||P!==w)){const Sn=P===w&&V.id===S;Ne.setState(V,P,Sn)}let et=!1;V.version===ut.__version?(ut.needsLights&&ut.lightsStateVersion!==hi.state.version||ut.outputColorSpace!==Z||H.isBatchedMesh&&ut.batching===!1||!H.isBatchedMesh&&ut.batching===!0||H.isInstancedMesh&&ut.instancing===!1||!H.isInstancedMesh&&ut.instancing===!0||H.isSkinnedMesh&&ut.skinning===!1||!H.isSkinnedMesh&&ut.skinning===!0||H.isInstancedMesh&&ut.instancingColor===!0&&H.instanceColor===null||H.isInstancedMesh&&ut.instancingColor===!1&&H.instanceColor!==null||H.isInstancedMesh&&ut.instancingMorph===!0&&H.morphTexture===null||H.isInstancedMesh&&ut.instancingMorph===!1&&H.morphTexture!==null||ut.envMap!==ge||V.fog===!0&&ut.fog!==ee||ut.numClippingPlanes!==void 0&&(ut.numClippingPlanes!==Ne.numPlanes||ut.numIntersection!==Ne.numIntersection)||ut.vertexAlphas!==Ae||ut.vertexTangents!==xe||ut.morphTargets!==Te||ut.morphNormals!==Le||ut.morphColors!==He||ut.toneMapping!==nt||ut.morphTargetsCount!==_t)&&(et=!0):(et=!0,ut.__version=V.version);let yi=ut.currentProgram;et===!0&&(yi=ts(V,U,H));let ds=!1,Pi=!1,Jt=!1;const bt=yi.getUniforms(),xn=ut.uniforms;if(Ee.useProgram(yi.program)&&(ds=!0,Pi=!0,Jt=!0),V.id!==S&&(S=V.id,Pi=!0),ds||w!==P){bt.setValue(Y,"projectionMatrix",P.projectionMatrix),bt.setValue(Y,"viewMatrix",P.matrixWorldInverse);const Sn=bt.map.cameraPosition;Sn!==void 0&&Sn.setValue(Y,je.setFromMatrixPosition(P.matrixWorld)),Se.logarithmicDepthBuffer&&bt.setValue(Y,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&bt.setValue(Y,"isOrthographic",P.isOrthographicCamera===!0),w!==P&&(w=P,Pi=!0,Jt=!0)}if(H.isSkinnedMesh){bt.setOptional(Y,H,"bindMatrix"),bt.setOptional(Y,H,"bindMatrixInverse");const Sn=H.skeleton;Sn&&(Sn.boneTexture===null&&Sn.computeBoneTexture(),bt.setValue(Y,"boneTexture",Sn.boneTexture,B))}H.isBatchedMesh&&(bt.setOptional(Y,H,"batchingTexture"),bt.setValue(Y,"batchingTexture",H._matricesTexture,B));const Fa=k.morphAttributes;(Fa.position!==void 0||Fa.normal!==void 0||Fa.color!==void 0)&&qe.update(H,k,yi),(Pi||ut.receiveShadow!==H.receiveShadow)&&(ut.receiveShadow=H.receiveShadow,bt.setValue(Y,"receiveShadow",H.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(xn.envMap.value=ge,xn.flipEnvMap.value=ge.isCubeTexture&&ge.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&U.environment!==null&&(V.userData&&V.userData.separateEnvMapIntensity?xn.envMapIntensity.value=V.envMapIntensity:xn.envMapIntensity.value=U.environmentIntensity),Pi&&(bt.setValue(Y,"toneMappingExposure",v.toneMappingExposure),ut.needsLights&&L(xn,Jt),ee&&V.fog===!0&&Ye.refreshFogUniforms(xn,ee),Ye.refreshMaterialUniforms(xn,V,K,W,v.userData.transmissionRenderTarget||g.state.transmissionRenderTarget),qf.upload(Y,Pt(ut),xn,B)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(qf.upload(Y,Pt(ut),xn,B),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&bt.setValue(Y,"center",H.center),bt.setValue(Y,"modelViewMatrix",H.modelViewMatrix),bt.setValue(Y,"normalMatrix",H.normalMatrix),bt.setValue(Y,"modelMatrix",H.matrixWorld);const Ns=V.extraUniformsToUpload;if(Ns&&Object.entries(Ns).forEach(([Sn,Xh])=>{Xh.needsUpdate!==!1&&bt.setValue(Y,Sn,Xh.value,B)}),V.isShaderMaterial||V.isRawShaderMaterial){const Sn=V.uniformsGroups;for(let Xh=0,b8=Sn.length;Xh<b8;Xh++){const hP=Sn[Xh];Nt.update(hP,yi),Nt.bind(hP,yi)}}return yi}function L(P,U){P.ambientLightColor.needsUpdate=U,P.lightProbe.needsUpdate=U,P.directionalLights.needsUpdate=U,P.directionalLightShadows.needsUpdate=U,P.pointLights.needsUpdate=U,P.pointLightShadows.needsUpdate=U,P.spotLights.needsUpdate=U,P.spotLightShadows.needsUpdate=U,P.rectAreaLights.needsUpdate=U,P.hemisphereLights.needsUpdate=U}function Q(P){return P.isMeshLambertMaterial||P.isMeshToonMaterial||P.isMeshPhongMaterial||P.isMeshStandardMaterial||P.isShadowMaterial||P.isShaderMaterial&&P.lights===!0}this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return E},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(P,U,k){N.get(P.texture).__webglTexture=U,N.get(P.depthTexture).__webglTexture=k;const V=N.get(P);V.__hasExternalTextures=!0,V.__autoAllocateDepthBuffer=k===void 0,V.__autoAllocateDepthBuffer||he.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),V.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(P,U){const k=N.get(P);k.__webglFramebuffer=U,k.__useDefaultFramebuffer=U===void 0},this.setRenderTarget=function(P,U=0,k=0){M=P,T=U,E=k;let V=!0,H=null,ee=!1,ne=!1;if(P){const ge=N.get(P);ge.__useDefaultFramebuffer!==void 0?(Ee.bindFramebuffer(Y.FRAMEBUFFER,null),V=!1):ge.__webglFramebuffer===void 0?B.setupRenderTarget(P):ge.__hasExternalTextures&&B.rebindTextures(P,N.get(P.texture).__webglTexture,N.get(P.depthTexture).__webglTexture);const Ae=P.texture;(Ae.isData3DTexture||Ae.isDataArrayTexture||Ae.isCompressedArrayTexture)&&(ne=!0);const xe=N.get(P).__webglFramebuffer;P.isWebGLCubeRenderTarget?(Array.isArray(xe[U])?H=xe[U][k]:H=xe[U],ee=!0):P.samples>0&&B.useMultisampledRTT(P)===!1?H=N.get(P).__webglMultisampledFramebuffer:Array.isArray(xe)?H=xe[k]:H=xe,C.copy(P.viewport),D.copy(P.scissor),O=P.scissorTest}else C.copy(re).multiplyScalar(K).floor(),D.copy(Ce).multiplyScalar(K).floor(),O=Ie;if(Ee.bindFramebuffer(Y.FRAMEBUFFER,H)&&V&&Ee.drawBuffers(P,H),Ee.viewport(C),Ee.scissor(D),Ee.setScissorTest(O),ee){const ge=N.get(P.texture);Y.framebufferTexture2D(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_CUBE_MAP_POSITIVE_X+U,ge.__webglTexture,k)}else if(ne){const ge=N.get(P.texture),Ae=U||0;Y.framebufferTextureLayer(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,ge.__webglTexture,k||0,Ae)}S=-1},this.readRenderTargetPixels=function(P,U,k,V,H,ee,ne,Z){if(!(P&&P.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let ge=N.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&ne!==void 0&&(ge=ge[ne]),ge){Ee.bindFramebuffer(Y.FRAMEBUFFER,ge);try{const Ae=Array.isArray(P.textures)?P.textures[Z||0]:P.texture,xe=Ae.format,Te=Ae.type;if(xe!==Kt&&Mt.convert(xe)!==Y.getParameter(Y.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const Le=Te===$t&&(he.has("EXT_color_buffer_half_float")||he.has("EXT_color_buffer_float"));if(Te!==Wt&&Mt.convert(Te)!==Y.getParameter(Y.IMPLEMENTATION_COLOR_READ_TYPE)&&Te!==zt&&!Le){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}U>=0&&U<=P.width-V&&k>=0&&k<=P.height-H&&((P.isWebGLMultipleRenderTargets||P.textures.length>1)&&Y.readBuffer(Y.COLOR_ATTACHMENT0+(Z||0)),Y.readPixels(U,k,V,H,Mt.convert(xe),Mt.convert(Te),ee))}finally{const Ae=M?N.get(M).__webglFramebuffer:null;Ee.bindFramebuffer(Y.FRAMEBUFFER,Ae)}}},this.copyFramebufferToTexture=function(P,U,k=0){const V=Math.pow(2,-k),H=Math.floor(U.image.width*V),ee=Math.floor(U.image.height*V);B.setTexture2D(U,0),Y.copyTexSubImage2D(Y.TEXTURE_2D,k,0,0,P.x,P.y,H,ee),Ee.unbindTexture()},this.copyTextureToTexture=function(P,U,k,V=0){const H=U.image.width,ee=U.image.height,ne=Mt.convert(k.format),Z=Mt.convert(k.type);B.setTexture2D(k,0),Y.pixelStorei(Y.UNPACK_FLIP_Y_WEBGL,k.flipY),Y.pixelStorei(Y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k.premultiplyAlpha),Y.pixelStorei(Y.UNPACK_ALIGNMENT,k.unpackAlignment),U.isDataTexture?Y.texSubImage2D(Y.TEXTURE_2D,V,P.x,P.y,H,ee,ne,Z,U.image.data):U.isCompressedTexture?Y.compressedTexSubImage2D(Y.TEXTURE_2D,V,P.x,P.y,U.mipmaps[0].width,U.mipmaps[0].height,ne,U.mipmaps[0].data):Y.texSubImage2D(Y.TEXTURE_2D,V,P.x,P.y,ne,Z,U.image),V===0&&k.generateMipmaps&&Y.generateMipmap(Y.TEXTURE_2D),Ee.unbindTexture()},this.copyTextureToTexture3D=function(P,U,k,V,H=0){const ee=Math.round(P.max.x-P.min.x),ne=Math.round(P.max.y-P.min.y),Z=P.max.z-P.min.z+1,ge=Mt.convert(V.format),Ae=Mt.convert(V.type);let xe;if(V.isData3DTexture)B.setTexture3D(V,0),xe=Y.TEXTURE_3D;else if(V.isDataArrayTexture||V.isCompressedArrayTexture)B.setTexture2DArray(V,0),xe=Y.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}Y.pixelStorei(Y.UNPACK_FLIP_Y_WEBGL,V.flipY),Y.pixelStorei(Y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,V.premultiplyAlpha),Y.pixelStorei(Y.UNPACK_ALIGNMENT,V.unpackAlignment);const Te=Y.getParameter(Y.UNPACK_ROW_LENGTH),Le=Y.getParameter(Y.UNPACK_IMAGE_HEIGHT),He=Y.getParameter(Y.UNPACK_SKIP_PIXELS),nt=Y.getParameter(Y.UNPACK_SKIP_ROWS),ni=Y.getParameter(Y.UNPACK_SKIP_IMAGES),_t=k.isCompressedTexture?k.mipmaps[H]:k.image;Y.pixelStorei(Y.UNPACK_ROW_LENGTH,_t.width),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,_t.height),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,P.min.x),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,P.min.y),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,P.min.z),k.isDataTexture||k.isData3DTexture?Y.texSubImage3D(xe,H,U.x,U.y,U.z,ee,ne,Z,ge,Ae,_t.data):V.isCompressedArrayTexture?Y.compressedTexSubImage3D(xe,H,U.x,U.y,U.z,ee,ne,Z,ge,_t.data):Y.texSubImage3D(xe,H,U.x,U.y,U.z,ee,ne,Z,ge,Ae,_t),Y.pixelStorei(Y.UNPACK_ROW_LENGTH,Te),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,Le),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,He),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,nt),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,ni),H===0&&V.generateMipmaps&&Y.generateMipmap(xe),Ee.unbindTexture()},this.initTexture=function(P){P.isCubeTexture?B.setTextureCube(P,0):P.isData3DTexture?B.setTexture3D(P,0):P.isDataArrayTexture||P.isCompressedArrayTexture?B.setTexture2DArray(P,0):B.setTexture2D(P,0),Ee.unbindTexture()},this.resetState=function(){T=0,E=0,M=null,Ee.reset(),Qt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ia}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===eu?"display-p3":"srgb",t.unpackColorSpace=Xt.workingColorSpace===tu?"display-p3":"srgb"}get useLegacyLights(){return this._useLegacyLights}set useLegacyLights(e){this._useLegacyLights=e}}class Yf{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new se(e),this.density=t}clone(){return new Yf(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class $f{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new se(e),this.near=t,this.far=i}clone(){return new $f(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class qa extends ft{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Tt,this.environmentIntensity=1,this.environmentRotation=new Tt,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Sc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Af,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Ss()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return su("THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,i){e*=this.stride,i*=t.stride;for(let n=0,s=this.stride;n<s;n++)this.array[e+n]=t.array[i+n];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ss()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(t,this.stride);return i.setUsage(this.usage),i}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Ss()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const as=new x;class On{constructor(e,t,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,i=this.data.count;t<i;t++)as.fromBufferAttribute(this,t),as.applyMatrix4(e),this.setXYZ(t,as.x,as.y,as.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)as.fromBufferAttribute(this,t),as.applyNormalMatrix(e),this.setXYZ(t,as.x,as.y,as.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)as.fromBufferAttribute(this,t),as.transformDirection(e),this.setXYZ(t,as.x,as.y,as.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=is(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=wt(i,this.array)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=is(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=is(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=is(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=is(t,this.array)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this}setXYZ(e,t,i,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array),n=wt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this}setXYZW(e,t,i,n,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=wt(t,this.array),i=wt(i,this.array),n=wt(n,this.array),s=wt(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this.data.array[e+3]=s,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[n+s])}return new Xe(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new On(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class du extends tn{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new se(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}let Ec;const fu=new x,Mc=new x,Tc=new x,Ic=new $,pu=new $,AC=new pe,Kf=new x,mu=new x,Jf=new x,yC=new $,ay=new $,vC=new $;class Zf extends ft{constructor(e=new du){if(super(),this.isSprite=!0,this.type="Sprite",Ec===void 0){Ec=new $e;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new Sc(t,5);Ec.setIndex([0,1,2,0,2,3]),Ec.setAttribute("position",new On(i,3,0,!1)),Ec.setAttribute("uv",new On(i,2,3,!1))}this.geometry=Ec,this.material=e,this.center=new $(.5,.5)}raycast(e,t){e.camera===null&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Mc.setFromMatrixScale(this.matrixWorld),AC.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Tc.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Mc.multiplyScalar(-Tc.z);const i=this.material.rotation;let n,s;i!==0&&(s=Math.cos(i),n=Math.sin(i));const a=this.center;ep(Kf.set(-.5,-.5,0),Tc,a,Mc,n,s),ep(mu.set(.5,-.5,0),Tc,a,Mc,n,s),ep(Jf.set(.5,.5,0),Tc,a,Mc,n,s),yC.set(0,0),ay.set(1,0),vC.set(1,1);let o=e.ray.intersectTriangle(Kf,mu,Jf,!1,fu);if(o===null&&(ep(mu.set(-.5,.5,0),Tc,a,Mc,n,s),ay.set(0,1),o=e.ray.intersectTriangle(Kf,Jf,mu,!1,fu),o===null))return;const l=e.ray.origin.distanceTo(fu);l<e.near||l>e.far||t.push({distance:l,point:fu.clone(),uv:ns.getInterpolation(fu,Kf,mu,Jf,yC,ay,vC,new $),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function ep(r,e,t,i,n,s){Ic.subVectors(r,t).addScalar(.5).multiply(i),n!==void 0?(pu.x=s*Ic.x-n*Ic.y,pu.y=n*Ic.x+s*Ic.y):pu.copy(Ic),r.copy(e),r.x+=pu.x,r.y+=pu.y,r.applyMatrix4(AC)}const tp=new x,_C=new x;class bC extends ft{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,n=t.length;i<n;i++){const s=t[i];this.addLevel(s.object.clone(),s.distance,s.hysteresis)}return this.autoUpdate=e.autoUpdate,this}addLevel(e,t=0,i=0){t=Math.abs(t);const n=this.levels;let s;for(s=0;s<n.length&&!(t<n[s].distance);s++);return n.splice(s,0,{distance:t,hysteresis:i,object:e}),this.add(e),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(e){const t=this.levels;if(t.length>0){let i,n;for(i=1,n=t.length;i<n;i++){let s=t[i].distance;if(t[i].object.visible&&(s-=s*t[i].hysteresis),e<s)break}return t[i-1].object}return null}raycast(e,t){if(this.levels.length>0){tp.setFromMatrixPosition(this.matrixWorld);const n=e.ray.origin.distanceTo(tp);this.getObjectForDistance(n).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){tp.setFromMatrixPosition(e.matrixWorld),_C.setFromMatrixPosition(this.matrixWorld);const i=tp.distanceTo(_C)/e.zoom;t[0].object.visible=!0;let n,s;for(n=1,s=t.length;n<s;n++){let a=t[n].distance;if(t[n].object.visible&&(a-=a*t[n].hysteresis),i>=a)t[n-1].object.visible=!1,t[n].object.visible=!0;else break}for(this._currentLevel=n-1;n<s;n++)t[n].object.visible=!1}}toJSON(e){const t=super.toJSON(e);this.autoUpdate===!1&&(t.object.autoUpdate=!1),t.object.levels=[];const i=this.levels;for(let n=0,s=i.length;n<s;n++){const a=i[n];t.object.levels.push({object:a.object.uuid,distance:a.distance,hysteresis:a.hysteresis})}return t}}const wC=new x,CC=new rt,xC=new rt,BL=new x,SC=new pe,ip=new x,oy=new un,EC=new pe,ly=new Ha;class np extends ye{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Fb,this.bindMatrix=new pe,this.bindMatrixInverse=new pe,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;this.boundingBox===null&&(this.boundingBox=new en),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,ip),this.boundingBox.expandByPoint(ip)}computeBoundingSphere(){const e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,ip),this.boundingSphere.expandByPoint(ip)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),oy.copy(this.boundingSphere),oy.applyMatrix4(n),e.ray.intersectsSphere(oy)!==!1&&(EC.copy(n).invert(),ly.copy(e.ray).applyMatrix4(EC),!(this.boundingBox!==null&&ly.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,ly)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const e=new rt,t=this.geometry.attributes.skinWeight;for(let i=0,n=t.count;i<n;i++){e.fromBufferAttribute(t,i);const s=1/e.manhattanLength();s!==1/0?e.multiplyScalar(s):e.set(1,0,0,0),t.setXYZW(i,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===Fb?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===xP?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const i=this.skeleton,n=this.geometry;CC.fromBufferAttribute(n.attributes.skinIndex,e),xC.fromBufferAttribute(n.attributes.skinWeight,e),wC.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let s=0;s<4;s++){const a=xC.getComponent(s);if(a!==0){const o=CC.getComponent(s);SC.multiplyMatrices(i.bones[o].matrixWorld,i.boneInverses[o]),t.addScaledVector(BL.copy(wC).applyMatrix4(SC),a)}}return t.applyMatrix4(this.bindMatrixInverse)}}class Pc extends ft{constructor(){super(),this.isBone=!0,this.type="Bone"}}class As extends Rt{constructor(e=null,t=1,i=1,n,s,a,o,l,c=pi,h=pi,u,d){super(null,a,o,l,c,h,n,s,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const MC=new pe,LL=new pe;class Dc{constructor(e=[],t=[]){this.uuid=Ss(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new pe)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const i=new pe;this.bones[e]&&i.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){const i=this.bones[e];i&&i.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){const i=this.bones[e];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const e=this.bones,t=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,a=e.length;s<a;s++){const o=e[s]?e[s].matrixWorld:LL;MC.multiplyMatrices(o,t[s]),MC.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new Dc(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const t=new Float32Array(e*e*4);t.set(this.boneMatrices);const i=new As(t,e,e,Kt,zt);return i.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=i,this}getBoneByName(e){for(let t=0,i=this.bones.length;t<i;t++){const n=this.bones[t];if(n.name===e)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let i=0,n=e.bones.length;i<n;i++){const s=e.bones[i];let a=t[s];a===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",s),a=new Pc),this.bones.push(a),this.boneInverses.push(new pe().fromArray(e.boneInverses[i]))}return this.init(),this}toJSON(){const e={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;const t=this.bones,i=this.boneInverses;for(let n=0,s=t.length;n<s;n++){const a=t[n];e.bones.push(a.uuid);const o=i[n];e.boneInverses.push(o.toArray())}return e}}class ha extends Xe{constructor(e,t,i,n=1){super(e,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Rc=new pe,TC=new pe,sp=[],IC=new en,OL=new pe,gu=new ye,Au=new un;class Bc extends ye{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new ha(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.sourceTrs=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,OL)}computeBoundingBox(){const e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new en),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Rc),IC.copy(e.boundingBox).applyMatrix4(Rc),this.boundingBox.union(IC)}computeBoundingSphere(){const e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new un),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Rc),Au.copy(e.boundingSphere).applyMatrix4(Rc),this.boundingSphere.union(Au)}copy(e,t){return super.copy(e,t),e.isInstancedMesh?(this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this):this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){const i=t.morphTargetInfluences,n=this.morphTexture.source.data.data,s=i.length+1,a=e*s+1;for(let o=0;o<i.length;o++)i[o]=n[a+o]}raycast(e,t){const i=this.matrixWorld,n=this.count;if(gu.geometry=this.geometry,gu.material=this.material,gu.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Au.copy(this.boundingSphere),Au.applyMatrix4(i),e.ray.intersectsSphere(Au)!==!1))for(let s=0;s<n;s++){this.getMatrixAt(s,Rc),TC.multiplyMatrices(i,Rc),gu.matrixWorld=TC,gu.raycast(e,sp);for(let a=0,o=sp.length;a<o;a++){const l=sp[a];l.instanceId=s,l.object=this,t.push(l)}sp.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new ha(new Float32Array(this.instanceMatrix.count*3),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){const i=t.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new As(new Float32Array(n*this.count),n,this.count,ka,zt));const s=this.morphTexture.source.data.data;let a=0;for(let c=0;c<i.length;c++)a+=i[c];const o=this.geometry.morphTargetsRelative?1:1-a,l=n*e;s[l]=o,s.set(i,l+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null),this}}function UL(r,e){return r.z-e.z}function FL(r,e){return e.z-r.z}class NL{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t){const i=this.pool,n=this.list;this.index>=i.length&&i.push({start:-1,count:-1,z:-1});const s=i[this.index];n.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=t}reset(){this.list.length=0,this.index=0}}const Lc="batchId",Xa=new pe,PC=new pe,kL=new pe,DC=new pe,cy=new hu,rp=new en,Qo=new un,yu=new x,hy=new NL,Qn=new ye,ap=[];function GL(r,e,t=0){const i=e.itemSize;if(r.isInterleavedBufferAttribute||r.array.constructor!==e.array.constructor){const n=r.count;for(let s=0;s<n;s++)for(let a=0;a<i;a++)e.setComponent(s+t,a,r.getComponent(s,a))}else e.array.set(r.array,t*i);e.needsUpdate=!0}class RC extends ye{get maxGeometryCount(){return this._maxGeometryCount}constructor(e,t,i=t*2,n){super(new $e,n),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._drawRanges=[],this._reservedRanges=[],this._visibility=[],this._active=[],this._bounds=[],this._maxGeometryCount=e,this._maxVertexCount=t,this._maxIndexCount=i,this._geometryInitialized=!1,this._geometryCount=0,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._visibilityChanged=!0,this._matricesTexture=null,this._initMatricesTexture()}_initMatricesTexture(){let e=Math.sqrt(this._maxGeometryCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const t=new Float32Array(e*e*4),i=new As(t,e,e,Kt,zt);this._matricesTexture=i}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxGeometryCount,s=this._maxIndexCount;if(this._geometryInitialized===!1){for(const o in e.attributes){const l=e.getAttribute(o),{array:c,itemSize:h,normalized:u}=l,d=new c.constructor(i*h),p=new Xe(d,h,u);t.setAttribute(o,p)}if(e.getIndex()!==null){const o=i>65536?new Uint32Array(s):new Uint16Array(s);t.setIndex(new Xe(o,1))}const a=n>65536?new Uint32Array(i):new Uint16Array(i);t.setAttribute(Lc,new Xe(a,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(Lc))throw new Error(`BatchedMesh: Geometry cannot use attribute "${Lc}"`);const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(i===Lc)continue;if(!e.hasAttribute(i))throw new Error(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new en);const e=this._geometryCount,t=this.boundingBox,i=this._active;t.makeEmpty();for(let n=0;n<e;n++)i[n]!==!1&&(this.getMatrixAt(n,Xa),this.getBoundingBoxAt(n,rp).applyMatrix4(Xa),t.union(rp))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un);const e=this._geometryCount,t=this.boundingSphere,i=this._active;t.makeEmpty();for(let n=0;n<e;n++)i[n]!==!1&&(this.getMatrixAt(n,Xa),this.getBoundingSphereAt(n,Qo).applyMatrix4(Xa),t.union(Qo))}addGeometry(e,t=-1,i=-1){if(this._initializeGeometry(e),this._validateGeometry(e),this._geometryCount>=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const n={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let s=null;const a=this._reservedRanges,o=this._drawRanges,l=this._bounds;this._geometryCount!==0&&(s=a[a.length-1]),t===-1?n.vertexCount=e.getAttribute("position").count:n.vertexCount=t,s===null?n.vertexStart=0:n.vertexStart=s.vertexStart+s.vertexCount;const c=e.getIndex(),h=c!==null;if(h&&(i===-1?n.indexCount=c.count:n.indexCount=i,s===null?n.indexStart=0:n.indexStart=s.indexStart+s.indexCount),n.indexStart!==-1&&n.indexStart+n.indexCount>this._maxIndexCount||n.vertexStart+n.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const u=this._visibility,d=this._active,p=this._matricesTexture,m=this._matricesTexture.image.data;u.push(!0),d.push(!0);const A=this._geometryCount;this._geometryCount++,kL.toArray(m,A*16),p.needsUpdate=!0,a.push(n),o.push({start:h?n.indexStart:n.vertexStart,count:-1}),l.push({boxInitialized:!1,box:new en,sphereInitialized:!1,sphere:new un});const g=this.geometry.getAttribute(Lc);for(let y=0;y<n.vertexCount;y++)g.setX(n.vertexStart+y,A);return g.needsUpdate=!0,this.setGeometryAt(A,e),A}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,s=i.getIndex(),a=t.getIndex(),o=this._reservedRanges[e];if(n&&a.count>o.indexCount||t.attributes.position.count>o.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.vertexCount;for(const p in i.attributes){if(p===Lc)continue;const m=t.getAttribute(p),A=i.getAttribute(p);GL(m,A,l);const g=m.itemSize;for(let y=m.count,_=c;y<_;y++){const v=l+y;for(let b=0;b<g;b++)A.setComponent(v,b,0)}A.needsUpdate=!0,A.addUpdateRange(l*g,c*g)}if(n){const p=o.indexStart;for(let m=0;m<a.count;m++)s.setX(p+m,l+a.getX(m));for(let m=a.count,A=o.indexCount;m<A;m++)s.setX(p+m,l);s.needsUpdate=!0,s.addUpdateRange(p,o.indexCount)}const h=this._bounds[e];t.boundingBox!==null?(h.box.copy(t.boundingBox),h.boxInitialized=!0):h.boxInitialized=!1,t.boundingSphere!==null?(h.sphere.copy(t.boundingSphere),h.sphereInitialized=!0):h.sphereInitialized=!1;const u=this._drawRanges[e],d=t.getAttribute("position");return u.count=n?a.count:d.count,this._visibilityChanged=!0,e}deleteGeometry(e){const t=this._active;return e>=t.length||t[e]===!1?this:(t[e]=!1,this._visibilityChanged=!0,this)}getBoundingBoxAt(e,t){if(this._active[e]===!1)return null;const n=this._bounds[e],s=n.box,a=this.geometry;if(n.boxInitialized===!1){s.makeEmpty();const o=a.index,l=a.attributes.position,c=this._drawRanges[e];for(let h=c.start,u=c.start+c.count;h<u;h++){let d=h;o&&(d=o.getX(d)),s.expandByPoint(yu.fromBufferAttribute(l,d))}n.boxInitialized=!0}return t.copy(s),t}getBoundingSphereAt(e,t){if(this._active[e]===!1)return null;const n=this._bounds[e],s=n.sphere,a=this.geometry;if(n.sphereInitialized===!1){s.makeEmpty(),this.getBoundingBoxAt(e,rp),rp.getCenter(s.center);const o=a.index,l=a.attributes.position,c=this._drawRanges[e];let h=0;for(let u=c.start,d=c.start+c.count;u<d;u++){let p=u;o&&(p=o.getX(p)),yu.fromBufferAttribute(l,p),h=Math.max(h,s.center.distanceToSquared(yu))}s.radius=Math.sqrt(h),n.sphereInitialized=!0}return t.copy(s),t}setMatrixAt(e,t){const i=this._active,n=this._matricesTexture,s=this._matricesTexture.image.data,a=this._geometryCount;return e>=a||i[e]===!1?this:(t.toArray(s,e*16),n.needsUpdate=!0,this)}getMatrixAt(e,t){const i=this._active,n=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||i[e]===!1?null:t.fromArray(n,e*16)}setVisibleAt(e,t){const i=this._visibility,n=this._active,s=this._geometryCount;return e>=s||n[e]===!1||i[e]===t?this:(i[e]=t,this._visibilityChanged=!0,this)}getVisibleAt(e){const t=this._visibility,i=this._active,n=this._geometryCount;return e>=n||i[e]===!1?!1:t[e]}raycast(e,t){const i=this._visibility,n=this._active,s=this._drawRanges,a=this._geometryCount,o=this.matrixWorld,l=this.geometry;Qn.material=this.material,Qn.geometry.index=l.index,Qn.geometry.attributes=l.attributes,Qn.geometry.boundingBox===null&&(Qn.geometry.boundingBox=new en),Qn.geometry.boundingSphere===null&&(Qn.geometry.boundingSphere=new un);for(let c=0;c<a;c++){if(!i[c]||!n[c])continue;const h=s[c];Qn.geometry.setDrawRange(h.start,h.count),this.getMatrixAt(c,Qn.matrixWorld).premultiply(o),this.getBoundingBoxAt(c,Qn.geometry.boundingBox),this.getBoundingSphereAt(c,Qn.geometry.boundingSphere),Qn.raycast(e,ap);for(let u=0,d=ap.length;u<d;u++){const p=ap[u];p.object=this,p.batchId=c,t.push(p)}ap.length=0}Qn.material=null,Qn.geometry.index=null,Qn.geometry.attributes={},Qn.geometry.setDrawRange(0,1/0)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.perObjectFrustumCulled=e.perObjectFrustumCulled,this.sortObjects=e.sortObjects,this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._drawRanges=e._drawRanges.map(t=>({...t})),this._reservedRanges=e._reservedRanges.map(t=>({...t})),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map(t=>({boxInitialized:t.boxInitialized,box:t.box.clone(),sphereInitialized:t.sphereInitialized,sphere:t.sphere.clone()})),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,t,i,n,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const a=n.getIndex(),o=a===null?1:a.array.BYTES_PER_ELEMENT,l=this._active,c=this._visibility,h=this._multiDrawStarts,u=this._multiDrawCounts,d=this._drawRanges,p=this.perObjectFrustumCulled;p&&(DC.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),cy.setFromProjectionMatrix(DC,e.coordinateSystem));let m=0;if(this.sortObjects){PC.copy(this.matrixWorld).invert(),yu.setFromMatrixPosition(i.matrixWorld).applyMatrix4(PC);for(let y=0,_=c.length;y<_;y++)if(c[y]&&l[y]){this.getMatrixAt(y,Xa),this.getBoundingSphereAt(y,Qo).applyMatrix4(Xa);let v=!1;if(p&&(v=!cy.intersectsSphere(Qo)),!v){const b=yu.distanceTo(Qo.center);hy.push(d[y],b)}}const A=hy.list,g=this.customSort;g===null?A.sort(s.transparent?FL:UL):g.call(this,A,i);for(let y=0,_=A.length;y<_;y++){const v=A[y];h[m]=v.start*o,u[m]=v.count,m++}hy.reset()}else for(let A=0,g=c.length;A<g;A++)if(c[A]&&l[A]){let y=!1;if(p&&(this.getMatrixAt(A,Xa),this.getBoundingSphereAt(A,Qo).applyMatrix4(Xa),y=!cy.intersectsSphere(Qo)),!y){const _=d[A];h[m]=_.start*o,u[m]=_.count,m++}}this._multiDrawCount=m,this._visibilityChanged=!1}onBeforeShadow(e,t,i,n,s,a){this.onBeforeRender(e,null,n,s,a)}}class Ei extends tn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new se(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const BC=new x,LC=new x,OC=new pe,uy=new Ha,op=new un;class fn extends ft{constructor(e=new $e,t=new Ei){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[0];for(let n=1,s=t.count;n<s;n++)BC.fromBufferAttribute(t,n-1),LC.fromBufferAttribute(t,n),i[n]=i[n-1],i[n]+=BC.distanceTo(LC);e.setAttribute("lineDistance",new Me(i,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const i=this.geometry,n=this.matrixWorld,s=e.params.Line.threshold,a=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),op.copy(i.boundingSphere),op.applyMatrix4(n),op.radius+=s,e.ray.intersectsSphere(op)===!1)return;OC.copy(n).invert(),uy.copy(e.ray).applyMatrix4(OC);const o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=new x,h=new x,u=new x,d=new x,p=this.isLineSegments?2:1,m=i.index,g=i.attributes.position;if(m!==null){const y=Math.max(0,a.start),_=Math.min(m.count,a.start+a.count);for(let v=y,b=_-1;v<b;v+=p){const T=m.getX(v),E=m.getX(v+1);if(c.fromBufferAttribute(g,T),h.fromBufferAttribute(g,E),uy.distanceSqToSegment(c,h,d,u)>l)continue;d.applyMatrix4(this.matrixWorld);const S=e.ray.origin.distanceTo(d);S<e.near||S>e.far||t.push({distance:S,point:u.clone().applyMatrix4(this.matrixWorld),index:v,face:null,faceIndex:null,object:this})}}else{const y=Math.max(0,a.start),_=Math.min(g.count,a.start+a.count);for(let v=y,b=_-1;v<b;v+=p){if(c.fromBufferAttribute(g,v),h.fromBufferAttribute(g,v+1),uy.distanceSqToSegment(c,h,d,u)>l)continue;d.applyMatrix4(this.matrixWorld);const E=e.ray.origin.distanceTo(d);E<e.near||E>e.far||t.push({distance:E,point:u.clone().applyMatrix4(this.matrixWorld),index:v,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=n.length;s<a;s++){const o=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}}const UC=new x,FC=new x;class Is extends fn{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let n=0,s=t.count;n<s;n+=2)UC.fromBufferAttribute(t,n),FC.fromBufferAttribute(t,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+UC.distanceTo(FC);e.setAttribute("lineDistance",new Me(i,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class dy extends fn{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class Tr extends tn{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new se(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const NC=new pe,fy=new Ha,lp=new un,cp=new x;class jo extends ft{constructor(e=new $e,t=new Tr){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){const i=this.geometry,n=this.matrixWorld,s=e.params.Points.threshold,a=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),lp.copy(i.boundingSphere),lp.applyMatrix4(n),lp.radius+=s,e.ray.intersectsSphere(lp)===!1)return;NC.copy(n).invert(),fy.copy(e.ray).applyMatrix4(NC);const o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=i.index,u=i.attributes.position;if(c!==null){const d=Math.max(0,a.start),p=Math.min(c.count,a.start+a.count);for(let m=d,A=p;m<A;m++){const g=c.getX(m);cp.fromBufferAttribute(u,g),kC(cp,g,l,n,e,t,this)}}else{const d=Math.max(0,a.start),p=Math.min(u.count,a.start+a.count);for(let m=d,A=p;m<A;m++)cp.fromBufferAttribute(u,m),kC(cp,m,l,n,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=n.length;s<a;s++){const o=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}}function kC(r,e,t,i,n,s,a){const o=fy.distanceSqToPoint(r);if(o<t){const l=new x;fy.closestPointToPoint(r,l),l.applyMatrix4(i);const c=n.ray.origin.distanceTo(l);if(c<n.near||c>n.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,object:a})}}class py extends Rt{constructor(e,t,i,n,s,a,o,l,c){super(e,t,i,n,s,a,o,l,c),this.isVideoTexture=!0,this.minFilter=a!==void 0?a:st,this.magFilter=s!==void 0?s:st,this.generateMipmaps=!1;const h=this;function u(){h.needsUpdate=!0,e.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(u)}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class zL extends Rt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=pi,this.minFilter=pi,this.generateMipmaps=!1,this.needsUpdate=!0}}class ua extends Rt{constructor(e,t,i,n,s,a,o,l,c,h,u,d){super(null,a,o,l,c,h,n,s,u,d),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class GC extends ua{constructor(e,t,i,n,s,a){super(e,t,i,s,a),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=ui}}class zC extends ua{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Kr),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class Wo extends Rt{constructor(e,t,i,n,s,a,o,l,c){super(e,t,i,n,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ps{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const i=this.getUtoTmapping(e);return this.getPoint(i,t)}getPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPoint(i/e));return t}getSpacedPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPointAt(i/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let i,n=this.getPoint(0),s=0;t.push(0);for(let a=1;a<=e;a++)i=this.getPoint(a/e),s+=i.distanceTo(n),t.push(s),n=i;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const i=this.getLengths();let n=0;const s=i.length;let a;t?a=t:a=e*i[s-1];let o=0,l=s-1,c;for(;o<=l;)if(n=Math.floor(o+(l-o)/2),c=i[n]-a,c<0)o=n+1;else if(c>0)l=n-1;else{l=n;break}if(n=l,i[n]===a)return n/(s-1);const h=i[n],d=i[n+1]-h,p=(a-h)/d;return(n+p)/(s-1)}getTangent(e,t){let n=e-1e-4,s=e+1e-4;n<0&&(n=0),s>1&&(s=1);const a=this.getPoint(n),o=this.getPoint(s),l=t||(a.isVector2?new $:new x);return l.copy(o).sub(a).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t){const i=new x,n=[],s=[],a=[],o=new x,l=new pe;for(let p=0;p<=e;p++){const m=p/e;n[p]=this.getTangentAt(m,new x)}s[0]=new x,a[0]=new x;let c=Number.MAX_VALUE;const h=Math.abs(n[0].x),u=Math.abs(n[0].y),d=Math.abs(n[0].z);h<=c&&(c=h,i.set(1,0,0)),u<=c&&(c=u,i.set(0,1,0)),d<=c&&i.set(0,0,1),o.crossVectors(n[0],i).normalize(),s[0].crossVectors(n[0],o),a[0].crossVectors(n[0],s[0]);for(let p=1;p<=e;p++){if(s[p]=s[p-1].clone(),a[p]=a[p-1].clone(),o.crossVectors(n[p-1],n[p]),o.length()>Number.EPSILON){o.normalize();const m=Math.acos(zi(n[p-1].dot(n[p]),-1,1));s[p].applyMatrix4(l.makeRotationAxis(o,m))}a[p].crossVectors(n[p],s[p])}if(t===!0){let p=Math.acos(zi(s[0].dot(s[e]),-1,1));p/=e,n[0].dot(o.crossVectors(s[0],s[e]))>0&&(p=-p);for(let m=1;m<=e;m++)s[m].applyMatrix4(l.makeRotationAxis(n[m],p*m)),a[m].crossVectors(n[m],s[m])}return{tangents:n,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class qo extends Ps{constructor(e=0,t=0,i=1,n=1,s=0,a=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=n,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new $){const i=t,n=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const a=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=n;for(;s>n;)s-=n;s<Number.EPSILON&&(a?s=0:s=n),this.aClockwise===!0&&!a&&(s===n?s=-n:s=s-n);const o=this.aStartAngle+e*s;let l=this.aX+this.xRadius*Math.cos(o),c=this.aY+this.yRadius*Math.sin(o);if(this.aRotation!==0){const h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=l-this.aX,p=c-this.aY;l=d*h-p*u+this.aX,c=d*u+p*h+this.aY}return i.set(l,c)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){const e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}}class hp extends qo{constructor(e,t,i,n,s,a){super(e,t,i,i,n,s,a),this.isArcCurve=!0,this.type="ArcCurve"}}function my(){let r=0,e=0,t=0,i=0;function n(s,a,o,l){r=s,e=o,t=-3*s+3*a-2*o-l,i=2*s-2*a+o+l}return{initCatmullRom:function(s,a,o,l,c){n(a,o,c*(o-s),c*(l-a))},initNonuniformCatmullRom:function(s,a,o,l,c,h,u){let d=(a-s)/c-(o-s)/(c+h)+(o-a)/h,p=(o-a)/h-(l-a)/(h+u)+(l-o)/u;d*=h,p*=h,n(a,o,d,p)},calc:function(s){const a=s*s,o=a*s;return r+e*s+t*a+i*o}}}const up=new x,gy=new my,Ay=new my,yy=new my;class Oc extends Ps{constructor(e=[],t=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=i,this.tension=n}getPoint(e,t=new x){const i=t,n=this.points,s=n.length,a=(s-(this.closed?0:1))*e;let o=Math.floor(a),l=a-o;this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/s)+1)*s:l===0&&o===s-1&&(o=s-2,l=1);let c,h;this.closed||o>0?c=n[(o-1)%s]:(up.subVectors(n[0],n[1]).add(n[0]),c=up);const u=n[o%s],d=n[(o+1)%s];if(this.closed||o+2<s?h=n[(o+2)%s]:(up.subVectors(n[s-1],n[s-2]).add(n[s-1]),h=up),this.curveType==="centripetal"||this.curveType==="chordal"){const p=this.curveType==="chordal"?.5:.25;let m=Math.pow(c.distanceToSquared(u),p),A=Math.pow(u.distanceToSquared(d),p),g=Math.pow(d.distanceToSquared(h),p);A<1e-4&&(A=1),m<1e-4&&(m=A),g<1e-4&&(g=A),gy.initNonuniformCatmullRom(c.x,u.x,d.x,h.x,m,A,g),Ay.initNonuniformCatmullRom(c.y,u.y,d.y,h.y,m,A,g),yy.initNonuniformCatmullRom(c.z,u.z,d.z,h.z,m,A,g)}else this.curveType==="catmullrom"&&(gy.initCatmullRom(c.x,u.x,d.x,h.x,this.tension),Ay.initCatmullRom(c.y,u.y,d.y,h.y,this.tension),yy.initCatmullRom(c.z,u.z,d.z,h.z,this.tension));return i.set(gy.calc(l),Ay.calc(l),yy.calc(l)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(n.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,i=this.points.length;t<i;t++){const n=this.points[t];e.points.push(n.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(new x().fromArray(n))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}}function VC(r,e,t,i,n){const s=(i-e)*.5,a=(n-t)*.5,o=r*r,l=r*o;return(2*t-2*i+s+a)*l+(-3*t+3*i-2*s-a)*o+s*r+t}function VL(r,e){const t=1-r;return t*t*e}function HL(r,e){return 2*(1-r)*r*e}function QL(r,e){return r*r*e}function vu(r,e,t,i){return VL(r,e)+HL(r,t)+QL(r,i)}function jL(r,e){const t=1-r;return t*t*t*e}function WL(r,e){const t=1-r;return 3*t*t*r*e}function qL(r,e){return 3*(1-r)*r*r*e}function XL(r,e){return r*r*r*e}function _u(r,e,t,i,n){return jL(r,e)+WL(r,t)+qL(r,i)+XL(r,n)}class bu extends Ps{constructor(e=new $,t=new $,i=new $,n=new $){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new $){const i=t,n=this.v0,s=this.v1,a=this.v2,o=this.v3;return i.set(_u(e,n.x,s.x,a.x,o.x),_u(e,n.y,s.y,a.y,o.y)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class dp extends Ps{constructor(e=new x,t=new x,i=new x,n=new x){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new x){const i=t,n=this.v0,s=this.v1,a=this.v2,o=this.v3;return i.set(_u(e,n.x,s.x,a.x,o.x),_u(e,n.y,s.y,a.y,o.y),_u(e,n.z,s.z,a.z,o.z)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class Xo extends Ps{constructor(e=new $,t=new $){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new $){const i=t;return e===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(e).add(this.v1)),i}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new $){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class Yo extends Ps{constructor(e=new x,t=new x){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new x){const i=t;return e===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(e).add(this.v1)),i}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new x){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class wu extends Ps{constructor(e=new $,t=new $,i=new $){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new $){const i=t,n=this.v0,s=this.v1,a=this.v2;return i.set(vu(e,n.x,s.x,a.x),vu(e,n.y,s.y,a.y)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class Cu extends Ps{constructor(e=new x,t=new x,i=new x){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new x){const i=t,n=this.v0,s=this.v1,a=this.v2;return i.set(vu(e,n.x,s.x,a.x),vu(e,n.y,s.y,a.y),vu(e,n.z,s.z,a.z)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class xu extends Ps{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new $){const i=t,n=this.points,s=(n.length-1)*e,a=Math.floor(s),o=s-a,l=n[a===0?a:a-1],c=n[a],h=n[a>n.length-2?n.length-1:a+1],u=n[a>n.length-3?n.length-1:a+2];return i.set(VC(o,l.x,c.x,h.x,u.x),VC(o,l.y,c.y,h.y,u.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,i=this.points.length;t<i;t++){const n=this.points[t];e.points.push(n.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(new $().fromArray(n))}return this}}var fp=Object.freeze({__proto__:null,ArcCurve:hp,CatmullRomCurve3:Oc,CubicBezierCurve:bu,CubicBezierCurve3:dp,EllipseCurve:qo,LineCurve:Xo,LineCurve3:Yo,QuadraticBezierCurve:wu,QuadraticBezierCurve3:Cu,SplineCurve:xu});class Su extends Ps{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(e){this.curves.push(e)}closePath(){const e=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);if(!e.equals(t)){const i=e.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new fp[i](t,e))}return this}getPoint(e,t){const i=e*this.getLength(),n=this.getCurveLengths();let s=0;for(;s<n.length;){if(n[s]>=i){const a=n[s]-i,o=this.curves[s],l=o.getLength(),c=l===0?0:1-a/l;return o.getPointAt(c,t)}s++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,n=this.curves.length;i<n;i++)t+=this.curves[i].getLength(),e.push(t);return this.cacheLengths=e,e}getSpacedPoints(e=40){const t=[];for(let i=0;i<=e;i++)t.push(this.getPoint(i/e));return this.autoClose&&t.push(t[0]),t}getPoints(e=12){const t=[];let i;for(let n=0,s=this.curves;n<s.length;n++){const a=s[n],o=a.isEllipseCurve?e*2:a.isLineCurve||a.isLineCurve3?1:a.isSplineCurve?e*a.points.length:e,l=a.getPoints(o);for(let c=0;c<l.length;c++){const h=l[c];i&&i.equals(h)||(t.push(h),i=h)}}return this.autoClose&&t.length>1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t<i;t++){const n=e.curves[t];this.curves.push(n.clone())}return this.autoClose=e.autoClose,this}toJSON(){const e=super.toJSON();e.autoClose=this.autoClose,e.curves=[];for(let t=0,i=this.curves.length;t<i;t++){const n=this.curves[t];e.curves.push(n.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.autoClose=e.autoClose,this.curves=[];for(let t=0,i=e.curves.length;t<i;t++){const n=e.curves[t];this.curves.push(new fp[n.type]().fromJSON(n))}return this}}class Uc extends Su{constructor(e){super(),this.type="Path",this.currentPoint=new $,e&&this.setFromPoints(e)}setFromPoints(e){this.moveTo(e[0].x,e[0].y);for(let t=1,i=e.length;t<i;t++)this.lineTo(e[t].x,e[t].y);return this}moveTo(e,t){return this.currentPoint.set(e,t),this}lineTo(e,t){const i=new Xo(this.currentPoint.clone(),new $(e,t));return this.curves.push(i),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,i,n){const s=new wu(this.currentPoint.clone(),new $(e,t),new $(i,n));return this.curves.push(s),this.currentPoint.set(i,n),this}bezierCurveTo(e,t,i,n,s,a){const o=new bu(this.currentPoint.clone(),new $(e,t),new $(i,n),new $(s,a));return this.curves.push(o),this.currentPoint.set(s,a),this}splineThru(e){const t=[this.currentPoint.clone()].concat(e),i=new xu(t);return this.curves.push(i),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,i,n,s,a){const o=this.currentPoint.x,l=this.currentPoint.y;return this.absarc(e+o,t+l,i,n,s,a),this}absarc(e,t,i,n,s,a){return this.absellipse(e,t,i,i,n,s,a),this}ellipse(e,t,i,n,s,a,o,l){const c=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(e+c,t+h,i,n,s,a,o,l),this}absellipse(e,t,i,n,s,a,o,l){const c=new qo(e,t,i,n,s,a,o,l);if(this.curves.length>0){const u=c.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(c);const h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Eu extends $e{constructor(e=[new $(0,-.5),new $(.5,0),new $(0,.5)],t=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:i,phiLength:n},t=Math.floor(t),n=zi(n,0,Math.PI*2);const s=[],a=[],o=[],l=[],c=[],h=1/t,u=new x,d=new $,p=new x,m=new x,A=new x;let g=0,y=0;for(let _=0;_<=e.length-1;_++)switch(_){case 0:g=e[_+1].x-e[_].x,y=e[_+1].y-e[_].y,p.x=y*1,p.y=-g,p.z=y*0,A.copy(p),p.normalize(),l.push(p.x,p.y,p.z);break;case e.length-1:l.push(A.x,A.y,A.z);break;default:g=e[_+1].x-e[_].x,y=e[_+1].y-e[_].y,p.x=y*1,p.y=-g,p.z=y*0,m.copy(p),p.x+=A.x,p.y+=A.y,p.z+=A.z,p.normalize(),l.push(p.x,p.y,p.z),A.copy(m)}for(let _=0;_<=t;_++){const v=i+_*h*n,b=Math.sin(v),T=Math.cos(v);for(let E=0;E<=e.length-1;E++){u.x=e[E].x*b,u.y=e[E].y,u.z=e[E].x*T,a.push(u.x,u.y,u.z),d.x=_/t,d.y=E/(e.length-1),o.push(d.x,d.y);const M=l[3*E+0]*b,S=l[3*E+1],w=l[3*E+0]*T;c.push(M,S,w)}}for(let _=0;_<t;_++)for(let v=0;v<e.length-1;v++){const b=v+_*e.length,T=b,E=b+e.length,M=b+e.length+1,S=b+1;s.push(T,E,S),s.push(M,S,E)}this.setIndex(s),this.setAttribute("position",new Me(a,3)),this.setAttribute("uv",new Me(o,2)),this.setAttribute("normal",new Me(c,3))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Eu(e.points,e.segments,e.phiStart,e.phiLength)}}class pp extends Eu{constructor(e=1,t=1,i=4,n=8){const s=new Uc;s.absarc(0,-t/2,e,Math.PI*1.5,0),s.absarc(0,t/2,e,0,Math.PI*.5),super(s.getPoints(i),n),this.type="CapsuleGeometry",this.parameters={radius:e,length:t,capSegments:i,radialSegments:n}}static fromJSON(e){return new pp(e.radius,e.length,e.capSegments,e.radialSegments)}}class mp extends $e{constructor(e=1,t=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:i,thetaLength:n},t=Math.max(3,t);const s=[],a=[],o=[],l=[],c=new x,h=new $;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let u=0,d=3;u<=t;u++,d+=3){const p=i+u/t*n;c.x=e*Math.cos(p),c.y=e*Math.sin(p),a.push(c.x,c.y,c.z),o.push(0,0,1),h.x=(a[d]/e+1)/2,h.y=(a[d+1]/e+1)/2,l.push(h.x,h.y)}for(let u=1;u<=t;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new Me(a,3)),this.setAttribute("normal",new Me(o,3)),this.setAttribute("uv",new Me(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new mp(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class sn extends $e{constructor(e=1,t=1,i=1,n=32,s=1,a=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:i,radialSegments:n,heightSegments:s,openEnded:a,thetaStart:o,thetaLength:l};const c=this;n=Math.floor(n),s=Math.floor(s);const h=[],u=[],d=[],p=[];let m=0;const A=[],g=i/2;let y=0;_(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(h),this.setAttribute("position",new Me(u,3)),this.setAttribute("normal",new Me(d,3)),this.setAttribute("uv",new Me(p,2));function _(){const b=new x,T=new x;let E=0;const M=(t-e)/i;for(let S=0;S<=s;S++){const w=[],C=S/s,D=C*(t-e)+e;for(let O=0;O<=n;O++){const F=O/n,G=F*l+o,j=Math.sin(G),W=Math.cos(G);T.x=D*j,T.y=-C*i+g,T.z=D*W,u.push(T.x,T.y,T.z),b.set(j,M,W).normalize(),d.push(b.x,b.y,b.z),p.push(F,1-C),w.push(m++)}A.push(w)}for(let S=0;S<n;S++)for(let w=0;w<s;w++){const C=A[w][S],D=A[w+1][S],O=A[w+1][S+1],F=A[w][S+1];h.push(C,D,F),h.push(D,O,F),E+=6}c.addGroup(y,E,0),y+=E}function v(b){const T=m,E=new $,M=new x;let S=0;const w=b===!0?e:t,C=b===!0?1:-1;for(let O=1;O<=n;O++)u.push(0,g*C,0),d.push(0,C,0),p.push(.5,.5),m++;const D=m;for(let O=0;O<=n;O++){const G=O/n*l+o,j=Math.cos(G),W=Math.sin(G);M.x=w*W,M.y=g*C,M.z=w*j,u.push(M.x,M.y,M.z),d.push(0,C,0),E.x=j*.5+.5,E.y=W*.5*C+.5,p.push(E.x,E.y),m++}for(let O=0;O<n;O++){const F=T+O,G=D+O;b===!0?h.push(G,G+1,F):h.push(G+1,G,F),S+=3}c.addGroup(y,S,b===!0?1:2),y+=S}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new sn(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class gp extends sn{constructor(e=1,t=1,i=32,n=1,s=!1,a=0,o=Math.PI*2){super(0,e,t,i,n,s,a,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:a,thetaLength:o}}static fromJSON(e){return new gp(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ya extends $e{constructor(e=[],t=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:i,detail:n};const s=[],a=[];o(n),c(i),h(),this.setAttribute("position",new Me(s,3)),this.setAttribute("normal",new Me(s.slice(),3)),this.setAttribute("uv",new Me(a,2)),n===0?this.computeVertexNormals():this.normalizeNormals();function o(_){const v=new x,b=new x,T=new x;for(let E=0;E<t.length;E+=3)p(t[E+0],v),p(t[E+1],b),p(t[E+2],T),l(v,b,T,_)}function l(_,v,b,T){const E=T+1,M=[];for(let S=0;S<=E;S++){M[S]=[];const w=_.clone().lerp(b,S/E),C=v.clone().lerp(b,S/E),D=E-S;for(let O=0;O<=D;O++)O===0&&S===E?M[S][O]=w:M[S][O]=w.clone().lerp(C,O/D)}for(let S=0;S<E;S++)for(let w=0;w<2*(E-S)-1;w++){const C=Math.floor(w/2);w%2===0?(d(M[S][C+1]),d(M[S+1][C]),d(M[S][C])):(d(M[S][C+1]),d(M[S+1][C+1]),d(M[S+1][C]))}}function c(_){const v=new x;for(let b=0;b<s.length;b+=3)v.x=s[b+0],v.y=s[b+1],v.z=s[b+2],v.normalize().multiplyScalar(_),s[b+0]=v.x,s[b+1]=v.y,s[b+2]=v.z}function h(){const _=new x;for(let v=0;v<s.length;v+=3){_.x=s[v+0],_.y=s[v+1],_.z=s[v+2];const b=g(_)/2/Math.PI+.5,T=y(_)/Math.PI+.5;a.push(b,1-T)}m(),u()}function u(){for(let _=0;_<a.length;_+=6){const v=a[_+0],b=a[_+2],T=a[_+4],E=Math.max(v,b,T),M=Math.min(v,b,T);E>.9&&M<.1&&(v<.2&&(a[_+0]+=1),b<.2&&(a[_+2]+=1),T<.2&&(a[_+4]+=1))}}function d(_){s.push(_.x,_.y,_.z)}function p(_,v){const b=_*3;v.x=e[b+0],v.y=e[b+1],v.z=e[b+2]}function m(){const _=new x,v=new x,b=new x,T=new x,E=new $,M=new $,S=new $;for(let w=0,C=0;w<s.length;w+=9,C+=6){_.set(s[w+0],s[w+1],s[w+2]),v.set(s[w+3],s[w+4],s[w+5]),b.set(s[w+6],s[w+7],s[w+8]),E.set(a[C+0],a[C+1]),M.set(a[C+2],a[C+3]),S.set(a[C+4],a[C+5]),T.copy(_).add(v).add(b).divideScalar(3);const D=g(T);A(E,C+0,_,D),A(M,C+2,v,D),A(S,C+4,b,D)}}function A(_,v,b,T){T<0&&_.x===1&&(a[v]=_.x-1),b.x===0&&b.z===0&&(a[v]=T/2/Math.PI+.5)}function g(_){return Math.atan2(_.z,-_.x)}function y(_){return Math.atan2(-_.y,Math.sqrt(_.x*_.x+_.z*_.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ya(e.vertices,e.indices,e.radius,e.details)}}class Ap extends Ya{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2,n=1/i,s=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-n,-i,0,-n,i,0,n,-i,0,n,i,-n,-i,0,-n,i,0,n,-i,0,n,i,0,-i,0,-n,i,0,-n,-i,0,n,i,0,n],a=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];super(s,a,e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Ap(e.radius,e.detail)}}const yp=new x,vp=new x,vy=new x,_p=new ns;class HC extends $e{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},e!==null){const n=Math.pow(10,4),s=Math.cos(Bo*t),a=e.getIndex(),o=e.getAttribute("position"),l=a?a.count:o.count,c=[0,0,0],h=["a","b","c"],u=new Array(3),d={},p=[];for(let m=0;m<l;m+=3){a?(c[0]=a.getX(m),c[1]=a.getX(m+1),c[2]=a.getX(m+2)):(c[0]=m,c[1]=m+1,c[2]=m+2);const{a:A,b:g,c:y}=_p;if(A.fromBufferAttribute(o,c[0]),g.fromBufferAttribute(o,c[1]),y.fromBufferAttribute(o,c[2]),_p.getNormal(vy),u[0]=`${Math.round(A.x*n)},${Math.round(A.y*n)},${Math.round(A.z*n)}`,u[1]=`${Math.round(g.x*n)},${Math.round(g.y*n)},${Math.round(g.z*n)}`,u[2]=`${Math.round(y.x*n)},${Math.round(y.y*n)},${Math.round(y.z*n)}`,!(u[0]===u[1]||u[1]===u[2]||u[2]===u[0]))for(let _=0;_<3;_++){const v=(_+1)%3,b=u[_],T=u[v],E=_p[h[_]],M=_p[h[v]],S=`${b}_${T}`,w=`${T}_${b}`;w in d&&d[w]?(vy.dot(d[w].normal)<=s&&(p.push(E.x,E.y,E.z),p.push(M.x,M.y,M.z)),d[w]=null):S in d||(d[S]={index0:c[_],index1:c[v],normal:vy.clone()})}}for(const m in d)if(d[m]){const{index0:A,index1:g}=d[m];yp.fromBufferAttribute(o,A),vp.fromBufferAttribute(o,g),p.push(yp.x,yp.y,yp.z),p.push(vp.x,vp.y,vp.z)}this.setAttribute("position",new Me(p,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}class ar extends Uc{constructor(e){super(e),this.uuid=Ss(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,n=this.holes.length;i<n;i++)t[i]=this.holes[i].getPoints(e);return t}extractPoints(e){return{shape:this.getPoints(e),holes:this.getPointsHoles(e)}}copy(e){super.copy(e),this.holes=[];for(let t=0,i=e.holes.length;t<i;t++){const n=e.holes[t];this.holes.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.uuid=this.uuid,e.holes=[];for(let t=0,i=this.holes.length;t<i;t++){const n=this.holes[t];e.holes.push(n.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.uuid=e.uuid,this.holes=[];for(let t=0,i=e.holes.length;t<i;t++){const n=e.holes[t];this.holes.push(new Uc().fromJSON(n))}return this}}const YL={triangulate:function(r,e,t=2){const i=e&&e.length,n=i?e[0]*t:r.length;let s=QC(r,0,n,t,!0);const a=[];if(!s||s.next===s.prev)return a;let o,l,c,h,u,d,p;if(i&&(s=eO(r,e,s,t)),r.length>80*t){o=c=r[0],l=h=r[1];for(let m=t;m<n;m+=t)u=r[m],d=r[m+1],u<o&&(o=u),d<l&&(l=d),u>c&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=p!==0?32767/p:0}return Mu(s,a,t,o,l,p,0),a}};function QC(r,e,t,i,n){let s,a;if(n===uO(r,e,t,i)>0)for(s=e;s<t;s+=i)a=qC(s,r[s],r[s+1],a);else for(s=t-i;s>=e;s-=i)a=qC(s,r[s],r[s+1],a);return a&&bp(a,a.next)&&(Iu(a),a=a.next),a}function $o(r,e){if(!r)return r;e||(e=r);let t=r,i;do if(i=!1,!t.steiner&&(bp(t,t.next)||Bi(t.prev,t,t.next)===0)){if(Iu(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Mu(r,e,t,i,n,s,a){if(!r)return;!a&&s&&rO(r,i,n,s);let o=r,l,c;for(;r.prev!==r.next;){if(l=r.prev,c=r.next,s?KL(r,i,n,s):$L(r)){e.push(l.i/t|0),e.push(r.i/t|0),e.push(c.i/t|0),Iu(r),r=c.next,o=c.next;continue}if(r=c,r===o){a?a===1?(r=JL($o(r),e,t),Mu(r,e,t,i,n,s,2)):a===2&&ZL(r,e,t,i,n,s):Mu($o(r),e,t,i,n,s,1);break}}}function $L(r){const e=r.prev,t=r,i=r.next;if(Bi(e,t,i)>=0)return!1;const n=e.x,s=t.x,a=i.x,o=e.y,l=t.y,c=i.y,h=n<s?n<a?n:a:s<a?s:a,u=o<l?o<c?o:c:l<c?l:c,d=n>s?n>a?n:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&Fc(n,o,s,l,a,c,m.x,m.y)&&Bi(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function KL(r,e,t,i){const n=r.prev,s=r,a=r.next;if(Bi(n,s,a)>=0)return!1;const o=n.x,l=s.x,c=a.x,h=n.y,u=s.y,d=a.y,p=o<l?o<c?o:c:l<c?l:c,m=h<u?h<d?h:d:u<d?u:d,A=o>l?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,y=_y(p,m,e,t,i),_=_y(A,g,e,t,i);let v=r.prevZ,b=r.nextZ;for(;v&&v.z>=y&&b&&b.z<=_;){if(v.x>=p&&v.x<=A&&v.y>=m&&v.y<=g&&v!==n&&v!==a&&Fc(o,h,l,u,c,d,v.x,v.y)&&Bi(v.prev,v,v.next)>=0||(v=v.prevZ,b.x>=p&&b.x<=A&&b.y>=m&&b.y<=g&&b!==n&&b!==a&&Fc(o,h,l,u,c,d,b.x,b.y)&&Bi(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;v&&v.z>=y;){if(v.x>=p&&v.x<=A&&v.y>=m&&v.y<=g&&v!==n&&v!==a&&Fc(o,h,l,u,c,d,v.x,v.y)&&Bi(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=_;){if(b.x>=p&&b.x<=A&&b.y>=m&&b.y<=g&&b!==n&&b!==a&&Fc(o,h,l,u,c,d,b.x,b.y)&&Bi(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function JL(r,e,t){let i=r;do{const n=i.prev,s=i.next.next;!bp(n,s)&&jC(n,i,i.next,s)&&Tu(n,s)&&Tu(s,n)&&(e.push(n.i/t|0),e.push(i.i/t|0),e.push(s.i/t|0),Iu(i),Iu(i.next),i=r=s),i=i.next}while(i!==r);return $o(i)}function ZL(r,e,t,i,n,s){let a=r;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&lO(a,o)){let l=WC(a,o);a=$o(a,a.next),l=$o(l,l.next),Mu(a,e,t,i,n,s,0),Mu(l,e,t,i,n,s,0);return}o=o.next}a=a.next}while(a!==r)}function eO(r,e,t,i){const n=[];let s,a,o,l,c;for(s=0,a=e.length;s<a;s++)o=e[s]*i,l=s<a-1?e[s+1]*i:r.length,c=QC(r,o,l,i,!1),c===c.next&&(c.steiner=!0),n.push(oO(c));for(n.sort(tO),s=0;s<n.length;s++)t=iO(n[s],t);return t}function tO(r,e){return r.x-e.x}function iO(r,e){const t=nO(r,e);if(!t)return e;const i=WC(t,r);return $o(i,i.next),$o(t,t.next)}function nO(r,e){let t=e,i=-1/0,n;const s=r.x,a=r.y;do{if(a<=t.y&&a>=t.next.y&&t.next.y!==t.y){const d=t.x+(a-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=s&&d>i&&(i=d,n=t.x<t.next.x?t:t.next,d===s))return n}t=t.next}while(t!==e);if(!n)return null;const o=n,l=n.x,c=n.y;let h=1/0,u;t=n;do s>=t.x&&t.x>=l&&s!==t.x&&Fc(a<c?s:i,a,l,c,a<c?i:s,a,t.x,t.y)&&(u=Math.abs(a-t.y)/(s-t.x),Tu(t,r)&&(u<h||u===h&&(t.x>n.x||t.x===n.x&&sO(n,t)))&&(n=t,h=u)),t=t.next;while(t!==o);return n}function sO(r,e){return Bi(r.prev,r,e.prev)<0&&Bi(e.next,r,r.next)<0}function rO(r,e,t,i){let n=r;do n.z===0&&(n.z=_y(n.x,n.y,e,t,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==r);n.prevZ.nextZ=null,n.prevZ=null,aO(n)}function aO(r){let e,t,i,n,s,a,o,l,c=1;do{for(t=r,r=null,s=null,a=0;t;){for(a++,i=t,o=0,e=0;e<c&&(o++,i=i.nextZ,!!i);e++);for(l=c;o>0||l>0&&i;)o!==0&&(l===0||!i||t.z<=i.z)?(n=t,t=t.nextZ,o--):(n=i,i=i.nextZ,l--),s?s.nextZ=n:r=n,n.prevZ=s,s=n;t=i}s.nextZ=null,c*=2}while(a>1);return r}function _y(r,e,t,i,n){return r=(r-t)*n|0,e=(e-i)*n|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function oO(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function Fc(r,e,t,i,n,s,a,o){return(n-a)*(e-o)>=(r-a)*(s-o)&&(r-a)*(i-o)>=(t-a)*(e-o)&&(t-a)*(s-o)>=(n-a)*(i-o)}function lO(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!cO(r,e)&&(Tu(r,e)&&Tu(e,r)&&hO(r,e)&&(Bi(r.prev,r,e.prev)||Bi(r,e.prev,e))||bp(r,e)&&Bi(r.prev,r,r.next)>0&&Bi(e.prev,e,e.next)>0)}function Bi(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function bp(r,e){return r.x===e.x&&r.y===e.y}function jC(r,e,t,i){const n=Cp(Bi(r,e,t)),s=Cp(Bi(r,e,i)),a=Cp(Bi(t,i,r)),o=Cp(Bi(t,i,e));return!!(n!==s&&a!==o||n===0&&wp(r,t,e)||s===0&&wp(r,i,e)||a===0&&wp(t,r,i)||o===0&&wp(t,e,i))}function wp(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Cp(r){return r>0?1:r<0?-1:0}function cO(r,e){let t=r;do{if(t.i!==r.i&&t.next.i!==r.i&&t.i!==e.i&&t.next.i!==e.i&&jC(t,t.next,r,e))return!0;t=t.next}while(t!==r);return!1}function Tu(r,e){return Bi(r.prev,r,r.next)<0?Bi(r,e,r.next)>=0&&Bi(r,r.prev,e)>=0:Bi(r,e,r.prev)<0||Bi(r,r.next,e)<0}function hO(r,e){let t=r,i=!1;const n=(r.x+e.x)/2,s=(r.y+e.y)/2;do t.y>s!=t.next.y>s&&t.next.y!==t.y&&n<(t.next.x-t.x)*(s-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==r);return i}function WC(r,e){const t=new by(r.i,r.x,r.y),i=new by(e.i,e.x,e.y),n=r.next,s=e.prev;return r.next=e,e.prev=r,t.next=n,n.prev=t,i.next=t,t.prev=i,s.next=i,i.prev=s,i}function qC(r,e,t,i){const n=new by(r,e,t);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function Iu(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function by(r,e,t){this.i=r,this.x=e,this.y=t,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function uO(r,e,t,i){let n=0;for(let s=e,a=t-i;s<t;s+=i)n+=(r[a]-r[s])*(r[s+1]+r[a+1]),a=s;return n}class or{static area(e){const t=e.length;let i=0;for(let n=t-1,s=0;s<t;n=s++)i+=e[n].x*e[s].y-e[s].x*e[n].y;return i*.5}static isClockWise(e){return or.area(e)<0}static triangulateShape(e,t){const i=[],n=[],s=[];XC(e),YC(i,e);let a=e.length;t.forEach(XC);for(let l=0;l<t.length;l++)n.push(a),a+=t[l].length,YC(i,t[l]);const o=YL.triangulate(i,n);for(let l=0;l<o.length;l+=3)s.push(o.slice(l,l+3));return s}}function XC(r){const e=r.length;e>2&&r[e-1].equals(r[0])&&r.pop()}function YC(r,e){for(let t=0;t<e.length;t++)r.push(e[t].x),r.push(e[t].y)}class xp extends $e{constructor(e=new ar([new $(.5,.5),new $(-.5,.5),new $(-.5,-.5),new $(.5,-.5)]),t={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:e,options:t},e=Array.isArray(e)?e:[e];const i=this,n=[],s=[];for(let o=0,l=e.length;o<l;o++){const c=e[o];a(c)}this.setAttribute("position",new Me(n,3)),this.setAttribute("uv",new Me(s,2)),this.computeVertexNormals();function a(o){const l=[],c=t.curveSegments!==void 0?t.curveSegments:12,h=t.steps!==void 0?t.steps:1,u=t.depth!==void 0?t.depth:1;let d=t.bevelEnabled!==void 0?t.bevelEnabled:!0,p=t.bevelThickness!==void 0?t.bevelThickness:.2,m=t.bevelSize!==void 0?t.bevelSize:p-.1,A=t.bevelOffset!==void 0?t.bevelOffset:0,g=t.bevelSegments!==void 0?t.bevelSegments:3;const y=t.extrudePath,_=t.UVGenerator!==void 0?t.UVGenerator:dO;let v,b=!1,T,E,M,S;y&&(v=y.getSpacedPoints(h),b=!0,d=!1,T=y.computeFrenetFrames(h,!1),E=new x,M=new x,S=new x),d||(g=0,p=0,m=0,A=0);const w=o.extractPoints(c);let C=w.shape;const D=w.holes;if(!or.isClockWise(C)){C=C.reverse();for(let fe=0,he=D.length;fe<he;fe++){const Se=D[fe];or.isClockWise(Se)&&(D[fe]=Se.reverse())}}const F=or.triangulateShape(C,D),G=C;for(let fe=0,he=D.length;fe<he;fe++){const Se=D[fe];C=C.concat(Se)}function j(fe,he,Se){return he||console.error("THREE.ExtrudeGeometry: vec does not exist"),fe.clone().addScaledVector(he,Se)}const W=C.length,K=F.length;function q(fe,he,Se){let Ee,De,N;const B=fe.x-he.x,J=fe.y-he.y,le=Se.x-fe.x,ue=Se.y-fe.y,ve=B*B+J*J,Ke=B*ue-J*le;if(Math.abs(Ke)>Number.EPSILON){const be=Math.sqrt(ve),Ye=Math.sqrt(le*le+ue*ue),at=he.x-J/be,Be=he.y+B/be,Ne=Se.x-ue/Ye,dt=Se.y+le/Ye,We=((Ne-at)*ue-(dt-Be)*le)/(B*ue-J*le);Ee=at+B*We-fe.x,De=Be+J*We-fe.y;const qe=Ee*Ee+De*De;if(qe<=2)return new $(Ee,De);N=Math.sqrt(qe/2)}else{let be=!1;B>Number.EPSILON?le>Number.EPSILON&&(be=!0):B<-Number.EPSILON?le<-Number.EPSILON&&(be=!0):Math.sign(J)===Math.sign(ue)&&(be=!0),be?(Ee=-J,De=B,N=Math.sqrt(ve)):(Ee=B,De=J,N=Math.sqrt(ve/2))}return new $(Ee/N,De/N)}const oe=[];for(let fe=0,he=G.length,Se=he-1,Ee=fe+1;fe<he;fe++,Se++,Ee++)Se===he&&(Se=0),Ee===he&&(Ee=0),oe[fe]=q(G[fe],G[Se],G[Ee]);const re=[];let Ce,Ie=oe.concat();for(let fe=0,he=D.length;fe<he;fe++){const Se=D[fe];Ce=[];for(let Ee=0,De=Se.length,N=De-1,B=Ee+1;Ee<De;Ee++,N++,B++)N===De&&(N=0),B===De&&(B=0),Ce[Ee]=q(Se[Ee],Se[N],Se[B]);re.push(Ce),Ie=Ie.concat(Ce)}for(let fe=0;fe<g;fe++){const he=fe/g,Se=p*Math.cos(he*Math.PI/2),Ee=m*Math.sin(he*Math.PI/2)+A;for(let De=0,N=G.length;De<N;De++){const B=j(G[De],oe[De],Ee);we(B.x,B.y,-Se)}for(let De=0,N=D.length;De<N;De++){const B=D[De];Ce=re[De];for(let J=0,le=B.length;J<le;J++){const ue=j(B[J],Ce[J],Ee);we(ue.x,ue.y,-Se)}}}const Ue=m+A;for(let fe=0;fe<W;fe++){const he=d?j(C[fe],Ie[fe],Ue):C[fe];b?(M.copy(T.normals[0]).multiplyScalar(he.x),E.copy(T.binormals[0]).multiplyScalar(he.y),S.copy(v[0]).add(M).add(E),we(S.x,S.y,S.z)):we(he.x,he.y,0)}for(let fe=1;fe<=h;fe++)for(let he=0;he<W;he++){const Se=d?j(C[he],Ie[he],Ue):C[he];b?(M.copy(T.normals[fe]).multiplyScalar(Se.x),E.copy(T.binormals[fe]).multiplyScalar(Se.y),S.copy(v[fe]).add(M).add(E),we(S.x,S.y,S.z)):we(Se.x,Se.y,u/h*fe)}for(let fe=g-1;fe>=0;fe--){const he=fe/g,Se=p*Math.cos(he*Math.PI/2),Ee=m*Math.sin(he*Math.PI/2)+A;for(let De=0,N=G.length;De<N;De++){const B=j(G[De],oe[De],Ee);we(B.x,B.y,u+Se)}for(let De=0,N=D.length;De<N;De++){const B=D[De];Ce=re[De];for(let J=0,le=B.length;J<le;J++){const ue=j(B[J],Ce[J],Ee);b?we(ue.x,ue.y+v[h-1].y,v[h-1].x+Se):we(ue.x,ue.y,u+Se)}}}te(),ce();function te(){const fe=n.length/3;if(d){let he=0,Se=W*he;for(let Ee=0;Ee<K;Ee++){const De=F[Ee];je(De[2]+Se,De[1]+Se,De[0]+Se)}he=h+g*2,Se=W*he;for(let Ee=0;Ee<K;Ee++){const De=F[Ee];je(De[0]+Se,De[1]+Se,De[2]+Se)}}else{for(let he=0;he<K;he++){const Se=F[he];je(Se[2],Se[1],Se[0])}for(let he=0;he<K;he++){const Se=F[he];je(Se[0]+W*h,Se[1]+W*h,Se[2]+W*h)}}i.addGroup(fe,n.length/3-fe,0)}function ce(){const fe=n.length/3;let he=0;me(G,he),he+=G.length;for(let Se=0,Ee=D.length;Se<Ee;Se++){const De=D[Se];me(De,he),he+=De.length}i.addGroup(fe,n.length/3-fe,1)}function me(fe,he){let Se=fe.length;for(;--Se>=0;){const Ee=Se;let De=Se-1;De<0&&(De=fe.length-1);for(let N=0,B=h+g*2;N<B;N++){const J=W*N,le=W*(N+1),ue=he+Ee+J,ve=he+De+J,Ke=he+De+le,be=he+Ee+le;ht(ue,ve,Ke,be)}}}function we(fe,he,Se){l.push(fe),l.push(he),l.push(Se)}function je(fe,he,Se){Ze(fe),Ze(he),Ze(Se);const Ee=n.length/3,De=_.generateTopUV(i,n,Ee-3,Ee-2,Ee-1);Y(De[0]),Y(De[1]),Y(De[2])}function ht(fe,he,Se,Ee){Ze(fe),Ze(he),Ze(Ee),Ze(he),Ze(Se),Ze(Ee);const De=n.length/3,N=_.generateSideWallUV(i,n,De-6,De-3,De-2,De-1);Y(N[0]),Y(N[1]),Y(N[3]),Y(N[1]),Y(N[2]),Y(N[3])}function Ze(fe){n.push(l[fe*3+0]),n.push(l[fe*3+1]),n.push(l[fe*3+2])}function Y(fe){s.push(fe.x),s.push(fe.y)}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON(),t=this.parameters.shapes,i=this.parameters.options;return fO(t,i,e)}static fromJSON(e,t){const i=[];for(let s=0,a=e.shapes.length;s<a;s++){const o=t[e.shapes[s]];i.push(o)}const n=e.options.extrudePath;return n!==void 0&&(e.options.extrudePath=new fp[n.type]().fromJSON(n)),new xp(i,e.options)}}const dO={generateTopUV:function(r,e,t,i,n){const s=e[t*3],a=e[t*3+1],o=e[i*3],l=e[i*3+1],c=e[n*3],h=e[n*3+1];return[new $(s,a),new $(o,l),new $(c,h)]},generateSideWallUV:function(r,e,t,i,n,s){const a=e[t*3],o=e[t*3+1],l=e[t*3+2],c=e[i*3],h=e[i*3+1],u=e[i*3+2],d=e[n*3],p=e[n*3+1],m=e[n*3+2],A=e[s*3],g=e[s*3+1],y=e[s*3+2];return Math.abs(o-h)<Math.abs(a-c)?[new $(a,1-l),new $(c,1-u),new $(d,1-m),new $(A,1-y)]:[new $(o,1-l),new $(h,1-u),new $(p,1-m),new $(g,1-y)]}};function fO(r,e,t){if(t.shapes=[],Array.isArray(r))for(let i=0,n=r.length;i<n;i++){const s=r[i];t.shapes.push(s.uuid)}else t.shapes.push(r.uuid);return t.options=Object.assign({},e),e.extrudePath!==void 0&&(t.options.extrudePath=e.extrudePath.toJSON()),t}class Sp extends Ya{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2,n=[-1,i,0,1,i,0,-1,-i,0,1,-i,0,0,-1,i,0,1,i,0,-1,-i,0,1,-i,i,0,-1,i,0,1,-i,0,-1,-i,0,1],s=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(n,s,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Sp(e.radius,e.detail)}}class da extends Ya{constructor(e=1,t=0){const i=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],n=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(i,n,e,t),this.type="OctahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new da(e.radius,e.detail)}}class Ep extends $e{constructor(e=.5,t=1,i=32,n=1,s=0,a=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:e,outerRadius:t,thetaSegments:i,phiSegments:n,thetaStart:s,thetaLength:a},i=Math.max(3,i),n=Math.max(1,n);const o=[],l=[],c=[],h=[];let u=e;const d=(t-e)/n,p=new x,m=new $;for(let A=0;A<=n;A++){for(let g=0;g<=i;g++){const y=s+g/i*a;p.x=u*Math.cos(y),p.y=u*Math.sin(y),l.push(p.x,p.y,p.z),c.push(0,0,1),m.x=(p.x/t+1)/2,m.y=(p.y/t+1)/2,h.push(m.x,m.y)}u+=d}for(let A=0;A<n;A++){const g=A*(i+1);for(let y=0;y<i;y++){const _=y+g,v=_,b=_+i+1,T=_+i+2,E=_+1;o.push(v,b,E),o.push(b,T,E)}}this.setIndex(o),this.setAttribute("position",new Me(l,3)),this.setAttribute("normal",new Me(c,3)),this.setAttribute("uv",new Me(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ep(e.innerRadius,e.outerRadius,e.thetaSegments,e.phiSegments,e.thetaStart,e.thetaLength)}}class Pu extends $e{constructor(e=new ar([new $(0,.5),new $(-.5,-.5),new $(.5,-.5)]),t=12){super(),this.type="ShapeGeometry",this.parameters={shapes:e,curveSegments:t};const i=[],n=[],s=[],a=[];let o=0,l=0;if(Array.isArray(e)===!1)c(e);else for(let h=0;h<e.length;h++)c(e[h]),this.addGroup(o,l,h),o+=l,l=0;this.setIndex(i),this.setAttribute("position",new Me(n,3)),this.setAttribute("normal",new Me(s,3)),this.setAttribute("uv",new Me(a,2));function c(h){const u=n.length/3,d=h.extractPoints(t);let p=d.shape;const m=d.holes;or.isClockWise(p)===!1&&(p=p.reverse());for(let g=0,y=m.length;g<y;g++){const _=m[g];or.isClockWise(_)===!0&&(m[g]=_.reverse())}const A=or.triangulateShape(p,m);for(let g=0,y=m.length;g<y;g++){const _=m[g];p=p.concat(_)}for(let g=0,y=p.length;g<y;g++){const _=p[g];n.push(_.x,_.y,0),s.push(0,0,1),a.push(_.x,_.y)}for(let g=0,y=A.length;g<y;g++){const _=A[g],v=_[0]+u,b=_[1]+u,T=_[2]+u;i.push(v,b,T),l+=3}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON(),t=this.parameters.shapes;return pO(t,e)}static fromJSON(e,t){const i=[];for(let n=0,s=e.shapes.length;n<s;n++){const a=t[e.shapes[n]];i.push(a)}return new Pu(i,e.curveSegments)}}function pO(r,e){if(e.shapes=[],Array.isArray(r))for(let t=0,i=r.length;t<i;t++){const n=r[t];e.shapes.push(n.uuid)}else e.shapes.push(r.uuid);return e}class Ds extends $e{constructor(e=1,t=32,i=16,n=0,s=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:s,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const l=Math.min(a+o,Math.PI);let c=0;const h=[],u=new x,d=new x,p=[],m=[],A=[],g=[];for(let y=0;y<=i;y++){const _=[],v=y/i;let b=0;y===0&&a===0?b=.5/t:y===i&&l===Math.PI&&(b=-.5/t);for(let T=0;T<=t;T++){const E=T/t;u.x=-e*Math.cos(n+E*s)*Math.sin(a+v*o),u.y=e*Math.cos(a+v*o),u.z=e*Math.sin(n+E*s)*Math.sin(a+v*o),m.push(u.x,u.y,u.z),d.copy(u).normalize(),A.push(d.x,d.y,d.z),g.push(E+b,1-v),_.push(c++)}h.push(_)}for(let y=0;y<i;y++)for(let _=0;_<t;_++){const v=h[y][_+1],b=h[y][_],T=h[y+1][_],E=h[y+1][_+1];(y!==0||a>0)&&p.push(v,b,E),(y!==i-1||l<Math.PI)&&p.push(b,T,E)}this.setIndex(p),this.setAttribute("position",new Me(m,3)),this.setAttribute("normal",new Me(A,3)),this.setAttribute("uv",new Me(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ds(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Mp extends Ya{constructor(e=1,t=0){const i=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],n=[2,1,0,0,3,2,1,3,0,2,3,1];super(i,n,e,t),this.type="TetrahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Mp(e.radius,e.detail)}}class $a extends $e{constructor(e=1,t=.4,i=12,n=48,s=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:e,tube:t,radialSegments:i,tubularSegments:n,arc:s},i=Math.floor(i),n=Math.floor(n);const a=[],o=[],l=[],c=[],h=new x,u=new x,d=new x;for(let p=0;p<=i;p++)for(let m=0;m<=n;m++){const A=m/n*s,g=p/i*Math.PI*2;u.x=(e+t*Math.cos(g))*Math.cos(A),u.y=(e+t*Math.cos(g))*Math.sin(A),u.z=t*Math.sin(g),o.push(u.x,u.y,u.z),h.x=e*Math.cos(A),h.y=e*Math.sin(A),d.subVectors(u,h).normalize(),l.push(d.x,d.y,d.z),c.push(m/n),c.push(p/i)}for(let p=1;p<=i;p++)for(let m=1;m<=n;m++){const A=(n+1)*p+m-1,g=(n+1)*(p-1)+m-1,y=(n+1)*(p-1)+m,_=(n+1)*p+m;a.push(A,g,_),a.push(g,y,_)}this.setIndex(a),this.setAttribute("position",new Me(o,3)),this.setAttribute("normal",new Me(l,3)),this.setAttribute("uv",new Me(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new $a(e.radius,e.tube,e.radialSegments,e.tubularSegments,e.arc)}}class Tp extends $e{constructor(e=1,t=.4,i=64,n=8,s=2,a=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:e,tube:t,tubularSegments:i,radialSegments:n,p:s,q:a},i=Math.floor(i),n=Math.floor(n);const o=[],l=[],c=[],h=[],u=new x,d=new x,p=new x,m=new x,A=new x,g=new x,y=new x;for(let v=0;v<=i;++v){const b=v/i*s*Math.PI*2;_(b,s,a,e,p),_(b+.01,s,a,e,m),g.subVectors(m,p),y.addVectors(m,p),A.crossVectors(g,y),y.crossVectors(A,g),A.normalize(),y.normalize();for(let T=0;T<=n;++T){const E=T/n*Math.PI*2,M=-t*Math.cos(E),S=t*Math.sin(E);u.x=p.x+(M*y.x+S*A.x),u.y=p.y+(M*y.y+S*A.y),u.z=p.z+(M*y.z+S*A.z),l.push(u.x,u.y,u.z),d.subVectors(u,p).normalize(),c.push(d.x,d.y,d.z),h.push(v/i),h.push(T/n)}}for(let v=1;v<=i;v++)for(let b=1;b<=n;b++){const T=(n+1)*(v-1)+(b-1),E=(n+1)*v+(b-1),M=(n+1)*v+b,S=(n+1)*(v-1)+b;o.push(T,E,S),o.push(E,M,S)}this.setIndex(o),this.setAttribute("position",new Me(l,3)),this.setAttribute("normal",new Me(c,3)),this.setAttribute("uv",new Me(h,2));function _(v,b,T,E,M){const S=Math.cos(v),w=Math.sin(v),C=T/b*v,D=Math.cos(C);M.x=E*(2+D)*.5*S,M.y=E*(2+D)*w*.5,M.z=E*Math.sin(C)*.5}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Tp(e.radius,e.tube,e.tubularSegments,e.radialSegments,e.p,e.q)}}class Du extends $e{constructor(e=new Cu(new x(-1,-1,0),new x(-1,1,0),new x(1,1,0)),t=64,i=1,n=8,s=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:i,radialSegments:n,closed:s};const a=e.computeFrenetFrames(t,s);this.tangents=a.tangents,this.normals=a.normals,this.binormals=a.binormals;const o=new x,l=new x,c=new $;let h=new x;const u=[],d=[],p=[],m=[];A(),this.setIndex(m),this.setAttribute("position",new Me(u,3)),this.setAttribute("normal",new Me(d,3)),this.setAttribute("uv",new Me(p,2));function A(){for(let v=0;v<t;v++)g(v);g(s===!1?t:0),_(),y()}function g(v){h=e.getPointAt(v/t,h);const b=a.normals[v],T=a.binormals[v];for(let E=0;E<=n;E++){const M=E/n*Math.PI*2,S=Math.sin(M),w=-Math.cos(M);l.x=w*b.x+S*T.x,l.y=w*b.y+S*T.y,l.z=w*b.z+S*T.z,l.normalize(),d.push(l.x,l.y,l.z),o.x=h.x+i*l.x,o.y=h.y+i*l.y,o.z=h.z+i*l.z,u.push(o.x,o.y,o.z)}}function y(){for(let v=1;v<=t;v++)for(let b=1;b<=n;b++){const T=(n+1)*(v-1)+(b-1),E=(n+1)*v+(b-1),M=(n+1)*v+b,S=(n+1)*(v-1)+b;m.push(T,E,S),m.push(E,M,S)}}function _(){for(let v=0;v<=t;v++)for(let b=0;b<=n;b++)c.x=v/t,c.y=b/n,p.push(c.x,c.y)}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new Du(new fp[e.path.type]().fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class Ip extends $e{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){const t=[],i=new Set,n=new x,s=new x;if(e.index!==null){const a=e.attributes.position,o=e.index;let l=e.groups;l.length===0&&(l=[{start:0,count:o.count,materialIndex:0}]);for(let c=0,h=l.length;c<h;++c){const u=l[c],d=u.start,p=u.count;for(let m=d,A=d+p;m<A;m+=3)for(let g=0;g<3;g++){const y=o.getX(m+g),_=o.getX(m+(g+1)%3);n.fromBufferAttribute(a,y),s.fromBufferAttribute(a,_),$C(n,s,i)===!0&&(t.push(n.x,n.y,n.z),t.push(s.x,s.y,s.z))}}}else{const a=e.attributes.position;for(let o=0,l=a.count/3;o<l;o++)for(let c=0;c<3;c++){const h=3*o+c,u=3*o+(c+1)%3;n.fromBufferAttribute(a,h),s.fromBufferAttribute(a,u),$C(n,s,i)===!0&&(t.push(n.x,n.y,n.z),t.push(s.x,s.y,s.z))}}this.setAttribute("position",new Me(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function $C(r,e,t){const i=`${r.x},${r.y},${r.z}-${e.x},${e.y},${e.z}`,n=`${e.x},${e.y},${e.z}-${r.x},${r.y},${r.z}`;return t.has(i)===!0||t.has(n)===!0?!1:(t.add(i),t.add(n),!0)}var KC=Object.freeze({__proto__:null,BoxGeometry:mi,CapsuleGeometry:pp,CircleGeometry:mp,ConeGeometry:gp,CylinderGeometry:sn,DodecahedronGeometry:Ap,EdgesGeometry:HC,ExtrudeGeometry:xp,IcosahedronGeometry:Sp,LatheGeometry:Eu,OctahedronGeometry:da,PlaneGeometry:Er,PolyhedronGeometry:Ya,RingGeometry:Ep,ShapeGeometry:Pu,SphereGeometry:Ds,TetrahedronGeometry:Mp,TorusGeometry:$a,TorusKnotGeometry:Tp,TubeGeometry:Du,WireframeGeometry:Ip});class JC extends tn{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new se(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class ZC extends nn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ka extends tn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new se(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 se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ks,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Tt,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nc extends Ka{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new $(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return zi(2.5*(this.ior-1)/(this.ior+1),0,2.5)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new se(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new se(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new se(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Ko extends tn{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new se(16777215),this.specular=new se(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ks,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Tt,this.combine=Xl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ex extends tn{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new se(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ks,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class wy extends tn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ks,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Cy extends tn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new se(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new se(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ks,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Tt,this.combine=Xl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class tx extends tn{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new se(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ks,this.normalScale=new $(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class ix extends Ei{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}function Jo(r,e,t){return!r||!t&&r.constructor===e?r:typeof e.BYTES_PER_ELEMENT=="number"?new e(r):Array.prototype.slice.call(r)}function nx(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function sx(r){function e(n,s){return r[n]-r[s]}const t=r.length,i=new Array(t);for(let n=0;n!==t;++n)i[n]=n;return i.sort(e),i}function xy(r,e,t){const i=r.length,n=new r.constructor(i);for(let s=0,a=0;a!==i;++s){const o=t[s]*e;for(let l=0;l!==e;++l)n[a++]=r[o+l]}return n}function Sy(r,e,t,i){let n=1,s=r[0];for(;s!==void 0&&s[i]===void 0;)s=r[n++];if(s===void 0)return;let a=s[i];if(a!==void 0)if(Array.isArray(a))do a=s[i],a!==void 0&&(e.push(s.time),t.push.apply(t,a)),s=r[n++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[i],a!==void 0&&(e.push(s.time),a.toArray(t,t.length)),s=r[n++];while(s!==void 0);else do a=s[i],a!==void 0&&(e.push(s.time),t.push(a)),s=r[n++];while(s!==void 0)}function mO(r,e,t,i,n=30){const s=r.clone();s.name=e;const a=[];for(let l=0;l<s.tracks.length;++l){const c=s.tracks[l],h=c.getValueSize(),u=[],d=[];for(let p=0;p<c.times.length;++p){const m=c.times[p]*n;if(!(m<t||m>=i)){u.push(c.times[p]);for(let A=0;A<h;++A)d.push(c.values[p*h+A])}}u.length!==0&&(c.times=Jo(u,c.times.constructor),c.values=Jo(d,c.values.constructor),a.push(c))}s.tracks=a;let o=1/0;for(let l=0;l<s.tracks.length;++l)o>s.tracks[l].times[0]&&(o=s.tracks[l].times[0]);for(let l=0;l<s.tracks.length;++l)s.tracks[l].shift(-1*o);return s.resetDuration(),s}function gO(r,e=0,t=r,i=30){i<=0&&(i=30);const n=t.tracks.length,s=e/i;for(let a=0;a<n;++a){const o=t.tracks[a],l=o.ValueTypeName;if(l==="bool"||l==="string")continue;const c=r.tracks.find(function(y){return y.name===o.name&&y.ValueTypeName===l});if(c===void 0)continue;let h=0;const u=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(h=u/3);let d=0;const p=c.getValueSize();c.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(d=p/3);const m=o.times.length-1;let A;if(s<=o.times[0]){const y=h,_=u-h;A=o.values.slice(y,_)}else if(s>=o.times[m]){const y=m*u+h,_=y+u-h;A=o.values.slice(y,_)}else{const y=o.createInterpolant(),_=h,v=u-h;y.evaluate(s),A=y.resultBuffer.slice(_,v)}l==="quaternion"&&new Qe().fromArray(A).normalize().conjugate().toArray(A);const g=c.times.length;for(let y=0;y<g;++y){const _=y*p+d;if(l==="quaternion")Qe.multiplyQuaternionsFlat(c.values,_,A,0,c.values,_);else{const v=p-d*2;for(let b=0;b<v;++b)c.values[_+b]-=A[b]}}}return r.blendMode=cw,r}const AO={convertArray:Jo,isTypedArray:nx,getKeyframeOrder:sx,sortedArray:xy,flattenJSON:Sy,subclip:mO,makeClipAdditive:gO};class kc{constructor(e,t,i,n){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=n!==void 0?n:new t.constructor(i),this.sampleValues=t,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(e){const t=this.parameterPositions;let i=this._cachedIndex,n=t[i],s=t[i-1];e:{t:{let a;i:{n:if(!(e<n)){for(let o=i+2;;){if(n===void 0){if(e<s)break n;return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===o)break;if(s=n,n=t[++i],e<n)break t}a=t.length;break i}if(!(e>=s)){const o=t[1];e<o&&(i=2,s=o);for(let l=i-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===l)break;if(n=s,s=t[--i-1],e>=s)break t}a=i,i=0;break i}break e}for(;i<a;){const o=i+a>>>1;e<t[o]?a=o:i=o+1}if(n=t[i],s=t[i-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===void 0)return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,s,n)}return this.interpolate_(i,s,e,n)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,s=e*n;for(let a=0;a!==n;++a)t[a]=i[s+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class rx extends kc{constructor(e,t,i,n){super(e,t,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Zl,endingEnd:Zl}}intervalChanged_(e,t,i){const n=this.parameterPositions;let s=e-2,a=e+1,o=n[s],l=n[a];if(o===void 0)switch(this.getSettings_().endingStart){case ec:s=e,o=2*t-i;break;case ff:s=n.length-2,o=t+n[s]-n[s+1];break;default:s=e,o=i}if(l===void 0)switch(this.getSettings_().endingEnd){case ec:a=e,l=2*i-t;break;case ff:a=1,l=i+n[1]-n[0];break;default:a=e-1,l=t}const c=(i-t)*.5,h=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(l-i),this._offsetPrev=s*h,this._offsetNext=a*h}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,p=this._weightNext,m=(i-t)/(n-t),A=m*m,g=A*m,y=-d*g+2*d*A-d*m,_=(1+d)*g+(-1.5-2*d)*A+(-.5+d)*m+1,v=(-1-p)*g+(1.5+p)*A+.5*m,b=p*g-p*A;for(let T=0;T!==o;++T)s[T]=y*a[h+T]+_*a[c+T]+v*a[l+T]+b*a[u+T];return s}}class Ey extends kc{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=(i-t)/(n-t),u=1-h;for(let d=0;d!==o;++d)s[d]=a[c+d]*u+a[l+d]*h;return s}}class ax extends kc{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e){return this.copySampleValue_(e-1)}}class lr{constructor(e,t,i,n){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Jo(t,this.TimeBufferType),this.values=Jo(i,this.ValueBufferType),this.setInterpolation(n||this.DefaultInterpolation)}static toJSON(e){const t=e.constructor;let i;if(t.toJSON!==this.toJSON)i=t.toJSON(e);else{i={name:e.name,times:Jo(e.times,Array),values:Jo(e.values,Array)};const n=e.getInterpolation();n!==e.DefaultInterpolation&&(i.interpolation=n)}return i.type=e.ValueTypeName,i}InterpolantFactoryMethodDiscrete(e){return new ax(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Ey(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new rx(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Jl:t=this.InterpolantFactoryMethodDiscrete;break;case Ro:t=this.InterpolantFactoryMethodLinear;break;case bA:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){const i="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(i);return console.warn("THREE.KeyframeTrack:",i),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Jl;case this.InterpolantFactoryMethodLinear:return Ro;case this.InterpolantFactoryMethodSmooth:return bA}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]+=e}return this}scale(e){if(e!==1){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]*=e}return this}trim(e,t){const i=this.times,n=i.length;let s=0,a=n-1;for(;s!==n&&i[s]<e;)++s;for(;a!==-1&&i[a]>t;)--a;if(++a,s!==0||a!==n){s>=a&&(a=Math.max(a,1),s=a-1);const o=this.getValueSize();this.times=i.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,n=this.values,s=i.length;s===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(n!==void 0&&nx(n))for(let o=0,l=n.length;o!==l;++o){const c=n[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===bA,s=e.length-1;let a=1;for(let o=1;o<s;++o){let l=!1;const c=e[o],h=e[o+1];if(c!==h&&(o!==1||c!==e[0]))if(n)l=!0;else{const u=o*i,d=u-i,p=u+i;for(let m=0;m!==i;++m){const A=t[u+m];if(A!==t[d+m]||A!==t[p+m]){l=!0;break}}}if(l){if(o!==a){e[a]=e[o];const u=o*i,d=a*i;for(let p=0;p!==i;++p)t[d+p]=t[u+p]}++a}}if(s>0){e[a]=e[s];for(let o=s*i,l=a*i,c=0;c!==i;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,n=new i(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}lr.prototype.TimeBufferType=Float32Array,lr.prototype.ValueBufferType=Float32Array,lr.prototype.DefaultInterpolation=Ro;class Zo extends lr{}Zo.prototype.ValueTypeName="bool",Zo.prototype.ValueBufferType=Array,Zo.prototype.DefaultInterpolation=Jl,Zo.prototype.InterpolantFactoryMethodLinear=void 0,Zo.prototype.InterpolantFactoryMethodSmooth=void 0;class My extends lr{}My.prototype.ValueTypeName="color";class Ja extends lr{}Ja.prototype.ValueTypeName="number";class ox extends kc{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(i-t)/(n-t);let c=e*o;for(let h=c+o;c!==h;c+=4)Qe.slerpFlat(s,0,a,c-o,a,c,l);return s}}class Ir extends lr{InterpolantFactoryMethodLinear(e){return new ox(this.times,this.values,this.getValueSize(),e)}}Ir.prototype.ValueTypeName="quaternion",Ir.prototype.DefaultInterpolation=Ro,Ir.prototype.InterpolantFactoryMethodSmooth=void 0;class el extends lr{}el.prototype.ValueTypeName="string",el.prototype.ValueBufferType=Array,el.prototype.DefaultInterpolation=Jl,el.prototype.InterpolantFactoryMethodLinear=void 0,el.prototype.InterpolantFactoryMethodSmooth=void 0;class Za extends lr{}Za.prototype.ValueTypeName="vector";class eo{constructor(e="",t=-1,i=[],n=wA){this.name=e,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=Ss(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,n=1/(e.fps||1);for(let a=0,o=i.length;a!==o;++a)t.push(vO(i[a]).scale(n));const s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){const t=[],i=e.tracks,n={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=i.length;s!==a;++s)t.push(lr.toJSON(i[s]));return n}static CreateFromMorphTargetSequence(e,t,i,n){const s=t.length,a=[];for(let o=0;o<s;o++){let l=[],c=[];l.push((o+s-1)%s,o,(o+1)%s),c.push(0,1,0);const h=sx(l);l=xy(l,1,h),c=xy(c,1,h),!n&&l[0]===0&&(l.push(s),c.push(c[0])),a.push(new Ja(".morphTargetInfluences["+t[o].name+"]",l,c).scale(1/i))}return new this(e,-1,a)}static findByName(e,t){let i=e;if(!Array.isArray(e)){const n=e;i=n.geometry&&n.geometry.animations||n.animations}for(let n=0;n<i.length;n++)if(i[n].name===t)return i[n];return null}static CreateClipsFromMorphTargetSequences(e,t,i){const n={},s=/^([\w-]*?)([\d]+)$/;for(let o=0,l=e.length;o<l;o++){const c=e[o],h=c.name.match(s);if(h&&h.length>1){const u=h[1];let d=n[u];d||(n[u]=d=[]),d.push(c)}}const a=[];for(const o in n)a.push(this.CreateFromMorphTargetSequence(o,n[o],t,i));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(u,d,p,m,A){if(p.length!==0){const g=[],y=[];Sy(p,g,y,m),g.length!==0&&A.push(new u(d,g,y))}},n=[],s=e.name||"default",a=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let u=0;u<c.length;u++){const d=c[u].keys;if(!(!d||d.length===0))if(d[0].morphTargets){const p={};let m;for(m=0;m<d.length;m++)if(d[m].morphTargets)for(let A=0;A<d[m].morphTargets.length;A++)p[d[m].morphTargets[A]]=-1;for(const A in p){const g=[],y=[];for(let _=0;_!==d[m].morphTargets.length;++_){const v=d[m];g.push(v.time),y.push(v.morphTarget===A?1:0)}n.push(new Ja(".morphTargetInfluence["+A+"]",g,y))}l=p.length*a}else{const p=".bones["+t[u].name+"]";i(Za,p+".position",d,"pos",n),i(Ir,p+".quaternion",d,"rot",n),i(Za,p+".scale",d,"scl",n)}}return n.length===0?null:new this(s,l,n,o)}resetDuration(){const e=this.tracks;let t=0;for(let i=0,n=e.length;i!==n;++i){const s=this.tracks[i];t=Math.max(t,s.times[s.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){const e=[];for(let i=0;i<this.tracks.length;i++)e.push(this.tracks[i].clone());const t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}}function yO(r){switch(r.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Ja;case"vector":case"vector2":case"vector3":case"vector4":return Za;case"color":return My;case"quaternion":return Ir;case"bool":case"boolean":return Zo;case"string":return el}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+r)}function vO(r){if(r.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=yO(r.type);if(r.times===void 0){const t=[],i=[];Sy(r.keys,t,i,"value"),r.times=t,r.values=i}return e.parse!==void 0?e.parse(r):new e(r.name,r.times,r.values,r.interpolation)}const di={enabled:!1,files:{},add:function(r,e){this.enabled!==!1&&(this.files[r]=e)},get:function(r,e){return this.enabled===!1?e?Promise.resolve():void 0:e?Promise.resolve(this.files[r]):this.files[r]},remove:function(r){delete this.files[r]},clear:function(){this.files={}}};class Pp{constructor(e,t,i){const n=this;let s=!1,a=0,o=0,l;const c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i,this.itemStart=function(h){o++,s===!1&&n.onStart!==void 0&&n.onStart(h,a,o),s=!0},this.itemEnd=function(h){a++,n.onProgress!==void 0&&n.onProgress(h,a,o),a===o&&(s=!1,n.onLoad!==void 0&&n.onLoad())},this.itemError=function(h){n.onError!==void 0&&n.onError(h)},this.resolveURL=function(h){return l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,u){return c.push(h,u),this},this.removeHandler=function(h){const u=c.indexOf(h);return u!==-1&&c.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=c.length;u<d;u+=2){const p=c[u],m=c[u+1];if(p.global&&(p.lastIndex=0),p.test(h))return m}return null}}}const Ty=new Pp;class li{constructor(e){this.manager=e!==void 0?e:Ty,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise(function(n,s){i.load(e,n,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}li.DEFAULT_MATERIAL_NAME="__DEFAULT";const fa={};class _O extends Error{constructor(e,t){super(e),this.response=t}}class Zt extends li{constructor(e){super(e),this.responseType="text",this.useCache=!0}load(e,t,i,n){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e),(this.useCache?di.get(e,this.responseType,this.mimeType):Promise.resolve(void 0)).then(s=>{if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(s),this.manager.itemEnd(e)},0),s;if(fa[e]!==void 0){fa[e].push({onLoad:t,onProgress:i,onError:n});return}fa[e]=[],fa[e].push({onLoad:t,onProgress:i,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const h=fa[e],u=c.body.getReader(),d=c.headers.get("Content-Length")||c.headers.get("X-File-Size"),p=d?parseInt(d):0,m=p!==0;let A=0;const g=new ReadableStream({start(y){_();function _(){u.read().then(({done:v,value:b})=>{if(v)y.close();else{A+=b.byteLength;const T=new ProgressEvent("progress",{lengthComputable:m,loaded:A,total:p});for(let E=0,M=h.length;E<M;E++){const S=h[E];S.onProgress&&S.onProgress(T)}y.enqueue(b),_()}})}}});return new Response(g)}else throw new _O(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return c.json();default:if(o===void 0)return c.text();{const u=/charset="?([^;"\s]*)"?/i.exec(o),d=u&&u[1]?u[1].toLowerCase():void 0,p=new TextDecoder(d);return c.arrayBuffer().then(m=>p.decode(m))}}}).then(c=>{this.useCache&&di.add(e,c,this.responseType);const h=fa[e];delete fa[e];for(let u=0,d=h.length;u<d;u++){const p=h[u];p.onLoad&&p.onLoad(c)}}).catch(c=>{const h=fa[e];if(h===void 0)throw this.manager.itemError(e),c;delete fa[e];for(let u=0,d=h.length;u<d;u++){const p=h[u];p.onError&&p.onError(c)}this.manager.itemError(e)}).finally(()=>{this.useCache&&this.manager.itemEnd(e)}),this.useCache&&this.manager.itemStart(e)})}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class bO extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new Zt(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t=[];for(let i=0;i<e.length;i++){const n=eo.parse(e[i]);t.push(n)}return t}}class lx extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=[],o=new ua,l=new Zt(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(s.withCredentials);let c=0;function h(u){l.load(e[u],function(d){const p=s.parse(d,!0);a[u]={width:p.width,height:p.height,format:p.format,mipmaps:p.mipmaps},c+=1,c===6&&(p.mipmapCount===1&&(o.minFilter=st),o.image=a,o.format=p.format,o.needsUpdate=!0,t&&t(o))},i,n)}if(Array.isArray(e))for(let u=0,d=e.length;u<d;++u)h(u);else l.load(e,function(u){const d=s.parse(u,!0);if(d.isCubemap){const p=d.mipmaps.length/d.mipmapCount;for(let m=0;m<p;m++){a[m]={mipmaps:[]};for(let A=0;A<d.mipmapCount;A++)a[m].mipmaps.push(d.mipmaps[m*d.mipmapCount+A]),a[m].format=d.format,a[m].width=d.width,a[m].height=d.height}o.image=a}else o.image.width=d.width,o.image.height=d.height,o.mipmaps=d.mipmaps;d.mipmapCount===1&&(o.minFilter=st),o.format=d.format,o.needsUpdate=!0,t&&t(o)},i,n);return o}}class Gc extends li{constructor(e){super(e)}load(e,t,i,n){const s=e;this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,o=di.get(e);if(o!==void 0)return a.manager.itemStart(e),setTimeout(function(){t&&t(o),a.manager.itemEnd(e)},0),o;const l=nu("img");function c(){u(),di.add(e,this),t&&t(this),a.manager.itemEnd(e)}function h(d){u(),n&&n(d),a.manager.itemError(e),a.manager.itemEnd(e)}function u(){l.removeEventListener("load",c,!1),l.removeEventListener("error",h,!1)}return l.addEventListener("load",c,!1),l.addEventListener("error",h,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(l.crossOrigin=this.crossOrigin),a.manager.itemStart(e),di.get(e,"blob").then(d=>{if(d!==void 0&&!d.type.startsWith("text/plain")){d.type||(e.endsWith(".svg")||e.startsWith("data:image/svg"))&&(d=new Blob([d],{type:"image/svg+xml"})),l.src=URL.createObjectURL(d);return}const p=new Zt(this.manager);p.useCache=!1,p.setPath(this.path),p.setCrossOrigin(this.crossOrigin),p.setResponseType("blob"),p.load(s,function(m){m.type||(e.endsWith(".svg")||e.startsWith("data:image/svg"))&&(m=new Blob([m],{type:"image/svg+xml"})),di.add(e,m,"blob"),l.src=URL.createObjectURL(m)},i,m=>{u(),n&&n(m)})}),l}}class wO extends li{constructor(e){super(e)}load(e,t,i,n){const s=new _c;s.colorSpace=vt;const a=new Gc(this.manager);a.setCrossOrigin(this.crossOrigin),a.setPath(this.path);let o=0;function l(c){a.load(e[c],function(h){s.images[c]=h,o++,o===6&&(s.needsUpdate=!0,t&&t(s))},void 0,n)}for(let c=0;c<e.length;++c)l(c);return s}}class Iy extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new As,o=new Zt(this.manager);return o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(s.withCredentials),o.load(e,function(l){let c;try{c=s.parse(l)}catch(h){if(n!==void 0)n(h);else{console.error(h);return}}c.image!==void 0?a.image=c.image:c.data!==void 0&&(a.image.width=c.width,a.image.height=c.height,a.image.data=c.data,a.image.complete=!0),a.wrapS=c.wrapS!==void 0?c.wrapS:ui,a.wrapT=c.wrapT!==void 0?c.wrapT:ui,a.magFilter=c.magFilter!==void 0?c.magFilter:st,a.minFilter=c.minFilter!==void 0?c.minFilter:st,a.anisotropy=c.anisotropy!==void 0?c.anisotropy:1,c.colorSpace!==void 0&&(a.colorSpace=c.colorSpace),c.flipY!==void 0&&(a.flipY=c.flipY),c.format!==void 0&&(a.format=c.format),c.type!==void 0&&(a.type=c.type),c.mipmaps!==void 0&&(a.mipmaps=c.mipmaps,a.minFilter=Ln),c.mipmapCount===1&&(a.minFilter=st),c.generateMipmaps!==void 0&&(a.generateMipmaps=c.generateMipmaps),a.needsUpdate=!0,t&&t(a,c)},i,n),a}}class to extends li{constructor(e){super(e)}load(e,t,i,n){const s=new Rt,a=new Gc(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){s.image=o,s.needsUpdate=!0,e.startsWith("blob:")||(s.userData.rootPath=a.path+e),t!==void 0&&t(s)},i,function(o){s.image instanceof ImageData&&(s.needsUpdate=!0),n!==void 0&&n(o)}),s}}class io extends ft{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new se(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),t}}class Dp extends io{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ft.DEFAULT_UP),this.updateMatrix(),this.groundColor=new se(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const Py=new pe,cx=new x,hx=new x;class Dy{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new $(512,512),this.map=null,this.mapPass=null,this.matrix=new pe,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new hu,this._frameExtents=new $(1,1),this._viewportCount=1,this._viewports=[new rt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,i=this.matrix;cx.setFromMatrixPosition(e.matrixWorld),t.position.copy(cx),hx.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(hx),t.updateMatrixWorld(),Py.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Py),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(Py)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.bias=e.bias,this.normalBias=e.normalBias,this.radius=e.radius,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class CO extends Dy{constructor(){super(new Vi(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,i=ic*2*e.angle*this.focus,n=this.mapSize.width/this.mapSize.height,s=e.distance||t.far;(i!==t.fov||n!==t.aspect||s!==t.far)&&(t.fov=i,t.aspect=n,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class zc extends io{constructor(e,t,i=0,n=Math.PI/3,s=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(ft.DEFAULT_UP),this.updateMatrix(),this.target=new ft,this.distance=i,this.angle=n,this.penumbra=s,this.decay=a,this.map=null,this.shadow=new CO}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}const ux=new pe,Ru=new x,Ry=new x;class xO extends Dy{constructor(){super(new Vi(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new $(4,2),this._viewportCount=6,this._viewports=[new rt(2,1,1,1),new rt(0,1,1,1),new rt(3,1,1,1),new rt(1,1,1,1),new rt(3,0,1,1),new rt(1,0,1,1)],this._cubeDirections=[new x(1,0,0),new x(-1,0,0),new x(0,0,1),new x(0,0,-1),new x(0,1,0),new x(0,-1,0)],this._cubeUps=[new x(0,1,0),new x(0,1,0),new x(0,1,0),new x(0,1,0),new x(0,0,1),new x(0,0,-1)]}updateMatrices(e,t=0){const i=this.camera,n=this.matrix,s=e.distance||i.far;s!==i.far&&(i.far=s,i.updateProjectionMatrix()),Ru.setFromMatrixPosition(e.matrixWorld),i.position.copy(Ru),Ry.copy(i.position),Ry.add(this._cubeDirections[t]),i.up.copy(this._cubeUps[t]),i.lookAt(Ry),i.updateMatrixWorld(),n.makeTranslation(-Ru.x,-Ru.y,-Ru.z),ux.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(ux)}}class tl extends io{constructor(e,t,i=0,n=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new xO}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class SO extends Dy{constructor(){super(new Mr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class il extends io{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ft.DEFAULT_UP),this.updateMatrix(),this.target=new ft,this.shadow=new SO}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Rp extends io{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Bp extends io{constructor(e,t,i=10,n=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=i,this.height=n}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class dx{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new x)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const i=e.x,n=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*n),t.addScaledVector(a[2],.488603*s),t.addScaledVector(a[3],.488603*i),t.addScaledVector(a[4],1.092548*(i*n)),t.addScaledVector(a[5],1.092548*(n*s)),t.addScaledVector(a[6],.315392*(3*s*s-1)),t.addScaledVector(a[7],1.092548*(i*s)),t.addScaledVector(a[8],.546274*(i*i-n*n)),t}getIrradianceAt(e,t){const i=e.x,n=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],2*.511664*n),t.addScaledVector(a[2],2*.511664*s),t.addScaledVector(a[3],2*.511664*i),t.addScaledVector(a[4],2*.429043*i*n),t.addScaledVector(a[5],2*.429043*n*s),t.addScaledVector(a[6],.743125*s*s-.247708),t.addScaledVector(a[7],2*.429043*i*s),t.addScaledVector(a[8],.429043*(i*i-n*n)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let i=0;i<9;i++)this.coefficients[i].addScaledVector(e.coefficients[i],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let i=0;i<9;i++)this.coefficients[i].lerp(e.coefficients[i],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].fromArray(e,t+n*3);return this}toArray(e=[],t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].toArray(e,t+n*3);return e}static getBasisAt(e,t){const i=e.x,n=e.y,s=e.z;t[0]=.282095,t[1]=.488603*n,t[2]=.488603*s,t[3]=.488603*i,t[4]=1.092548*i*n,t[5]=1.092548*n*s,t[6]=.315392*(3*s*s-1),t[7]=1.092548*i*s,t[8]=.546274*(i*i-n*n)}}class fx extends io{constructor(e=new dx,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class Bu extends li{constructor(e){super(e),this.textures={}}load(e,t,i,n){const s=this,a=new Zt(s.manager);a.setPath(s.path),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(e,function(o){try{t(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t=this.textures;function i(a){return t[a]===void 0&&console.warn("THREE.MaterialLoader: Undefined texture",a),t[a]}const n=e.metadata&&e.metadata.version<=4.5?Dt:void 0,s=Bu.createMaterialFromType(e.type);if(e.uuid!==void 0&&(s.uuid=e.uuid),e.name!==void 0&&(s.name=e.name),e.color!==void 0&&s.color!==void 0&&s.color.setHex(e.color,n),e.roughness!==void 0&&(s.roughness=e.roughness),e.metalness!==void 0&&(s.metalness=e.metalness),e.sheen!==void 0&&(s.sheen=e.sheen),e.sheenColor!==void 0&&(s.sheenColor=new se().setHex(e.sheenColor,n)),e.sheenRoughness!==void 0&&(s.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&s.emissive!==void 0&&s.emissive.setHex(e.emissive,n),e.specular!==void 0&&s.specular!==void 0&&s.specular.setHex(e.specular,n),e.specularIntensity!==void 0&&(s.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&s.specularColor!==void 0&&s.specularColor.setHex(e.specularColor,n),e.shininess!==void 0&&(s.shininess=e.shininess),e.clearcoat!==void 0&&(s.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=e.clearcoatRoughness),e.iridescence!==void 0&&(s.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(s.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(s.transmission=e.transmission),e.thickness!==void 0&&(s.thickness=e.thickness),e.attenuationDistance!==void 0&&(s.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&s.attenuationColor!==void 0&&s.attenuationColor.setHex(e.attenuationColor,n),e.anisotropy!==void 0&&(s.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(s.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(s.fog=e.fog),e.flatShading!==void 0&&(s.flatShading=e.flatShading),e.blending!==void 0&&(s.blending=e.blending),e.combine!==void 0&&(s.combine=e.combine),e.side!==void 0&&(s.side=e.side),e.shadowSide!==void 0&&(s.shadowSide=e.shadowSide),e.opacity!==void 0&&(s.opacity=e.opacity),e.transparent!==void 0&&(s.transparent=e.transparent),e.alphaTest!==void 0&&(s.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(s.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(s.depthFunc=e.depthFunc),e.depthTest!==void 0&&(s.depthTest=e.depthTest),e.depthWrite!==void 0&&(s.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(s.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(s.blendSrc=e.blendSrc),e.blendDst!==void 0&&(s.blendDst=e.blendDst),e.blendEquation!==void 0&&(s.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(s.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(s.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(s.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&s.blendColor!==void 0&&s.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(s.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(s.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(s.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(s.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(s.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(s.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(s.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(s.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(s.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(s.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(s.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(s.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(s.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(s.rotation=e.rotation),e.linewidth!==void 0&&(s.linewidth=e.linewidth),e.dashSize!==void 0&&(s.dashSize=e.dashSize),e.gapSize!==void 0&&(s.gapSize=e.gapSize),e.scale!==void 0&&(s.scale=e.scale),e.polygonOffset!==void 0&&(s.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(s.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(s.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(s.dithering=e.dithering),e.alphaToCoverage!==void 0&&(s.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(s.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(s.forceSinglePass=e.forceSinglePass),e.visible!==void 0&&(s.visible=e.visible),e.toneMapped!==void 0&&(s.toneMapped=e.toneMapped),e.userData!==void 0&&(s.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?s.vertexColors=e.vertexColors>0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const o=e.uniforms[a];switch(s.uniforms[a]={},o.type){case"t":s.uniforms[a].value=i(o.value);break;case"c":s.uniforms[a].value=new se().setHex(o.value,n);break;case"v2":s.uniforms[a].value=new $().fromArray(o.value);break;case"v3":s.uniforms[a].value=new x().fromArray(o.value);break;case"v4":s.uniforms[a].value=new rt().fromArray(o.value);break;case"m3":s.uniforms[a].value=new mt().fromArray(o.value);break;case"m4":s.uniforms[a].value=new pe().fromArray(o.value);break;default:s.uniforms[a].value=o.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new $().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new $().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}static createMaterialFromType(e){const t={ShadowMaterial:JC,SpriteMaterial:du,RawShaderMaterial:ZC,ShaderMaterial:nn,PointsMaterial:Tr,MeshPhysicalMaterial:Nc,MeshStandardMaterial:Ka,MeshPhongMaterial:Ko,MeshToonMaterial:ex,MeshNormalMaterial:wy,MeshLambertMaterial:Cy,MeshDepthMaterial:xc,MeshDistanceMaterial:sy,MeshBasicMaterial:ss,MeshMatcapMaterial:tx,LineDashedMaterial:ix,LineBasicMaterial:Ei,Material:tn};return new t[e]}}class Rs{static decodeText(e){if(typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let i=0,n=e.length;i<n;i++)t+=String.fromCharCode(e[i]);try{return decodeURIComponent(escape(t))}catch{return t}}static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){if(typeof e!="string"||e==="")return"";if(e[0]==="/")if(/^https?:\/\//i.test(t))t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1");else return e;return/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e}}class By extends $e{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class Ly extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new Zt(s.manager);a.setPath(s.path),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(e,function(o){try{t(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t={},i={};function n(p,m){if(t[m]!==void 0)return t[m];const g=p.interleavedBuffers[m],y=s(p,g.buffer),_=nc(g.type,y),v=new Sc(_,g.stride);return v.uuid=g.uuid,t[m]=v,v}function s(p,m){if(i[m]!==void 0)return i[m];const g=p.arrayBuffers[m],y=new Uint32Array(g).buffer;return i[m]=y,y}const a=e.isInstancedBufferGeometry?new By:new $e,o=e.data.index;if(o!==void 0){const p=nc(o.type,o.array);a.setIndex(new Xe(p,1))}const l=e.data.attributes;for(const p in l){const m=l[p];let A;if(m.isInterleavedBufferAttribute){const g=n(e.data,m.data);A=new On(g,m.itemSize,m.offset,m.normalized)}else{const g=nc(m.type,m.array),y=m.isInstancedBufferAttribute?ha:Xe;A=new y(g,m.itemSize,m.normalized)}m.name!==void 0&&(A.name=m.name),m.usage!==void 0&&A.setUsage(m.usage),a.setAttribute(p,A)}const c=e.data.morphAttributes;if(c)for(const p in c){const m=c[p],A=[];for(let g=0,y=m.length;g<y;g++){const _=m[g];let v;if(_.isInterleavedBufferAttribute){const b=n(e.data,_.data);v=new On(b,_.itemSize,_.offset,_.normalized)}else{const b=nc(_.type,_.array);v=new Xe(b,_.itemSize,_.normalized)}_.name!==void 0&&(v.name=_.name),A.push(v)}a.morphAttributes[p]=A}e.data.morphTargetsRelative&&(a.morphTargetsRelative=!0);const u=e.data.groups||e.data.drawcalls||e.data.offsets;if(u!==void 0)for(let p=0,m=u.length;p!==m;++p){const A=u[p];a.addGroup(A.start,A.count,A.materialIndex)}const d=e.data.boundingSphere;if(d!==void 0){const p=new x;d.center!==void 0&&p.fromArray(d.center),a.boundingSphere=new un(p,d.radius)}return e.name&&(a.name=e.name),e.userData&&(a.userData=e.userData),a}}class Lp extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=this.path===""?Rs.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||a;const o=new Zt(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){let c=null;try{c=JSON.parse(l)}catch(u){n!==void 0&&n(u),console.error("THREE:ObjectLoader: Can't parse "+e+".",u.message);return}const h=c.metadata;if(h===void 0||h.type===void 0||h.type.toLowerCase()==="geometry"){n!==void 0&&n(new Error("THREE.ObjectLoader: Can't load "+e)),console.error("THREE.ObjectLoader: Can't load "+e);return}s.parse(c,t)},i,n)}async loadAsync(e,t){const i=this,n=this.path===""?Rs.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||n;const s=new Zt(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials);const a=await s.loadAsync(e,t),o=JSON.parse(a),l=o.metadata;if(l===void 0||l.type===void 0||l.type.toLowerCase()==="geometry")throw new Error("THREE.ObjectLoader: Can't load "+e);return await i.parseAsync(o)}parse(e,t){const i=this.parseAnimations(e.animations),n=this.parseShapes(e.shapes),s=this.parseGeometries(e.geometries,n),a=this.parseImages(e.images,function(){t!==void 0&&t(c)}),o=this.parseTextures(e.textures,a),l=this.parseMaterials(e.materials,o),c=this.parseObject(e.object,s,l,o,i),h=this.parseSkeletons(e.skeletons,c);if(this.bindSkeletons(c,h),t!==void 0){let u=!1;for(const d in a)if(a[d].data instanceof HTMLImageElement){u=!0;break}u===!1&&t(c)}return c}async parseAsync(e){const t=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),n=this.parseGeometries(e.geometries,i),s=await this.parseImagesAsync(e.images),a=this.parseTextures(e.textures,s),o=this.parseMaterials(e.materials,a),l=this.parseObject(e.object,n,o,a,t),c=this.parseSkeletons(e.skeletons,l);return this.bindSkeletons(l,c),l}parseShapes(e){const t={};if(e!==void 0)for(let i=0,n=e.length;i<n;i++){const s=new ar().fromJSON(e[i]);t[s.uuid]=s}return t}parseSkeletons(e,t){const i={},n={};if(t.traverse(function(s){s.isBone&&(n[s.uuid]=s)}),e!==void 0)for(let s=0,a=e.length;s<a;s++){const o=new Dc().fromJSON(e[s],n);i[o.uuid]=o}return i}parseGeometries(e,t){const i={};if(e!==void 0){const n=new Ly;for(let s=0,a=e.length;s<a;s++){let o;const l=e[s];switch(l.type){case"BufferGeometry":case"InstancedBufferGeometry":o=n.parse(l);break;default:l.type in KC?o=KC[l.type].fromJSON(l,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${l.type}"`)}o.uuid=l.uuid,l.name!==void 0&&(o.name=l.name),l.userData!==void 0&&(o.userData=l.userData),i[l.uuid]=o}}return i}parseMaterials(e,t){const i={},n={};if(e!==void 0){const s=new Bu;s.setTextures(t);for(let a=0,o=e.length;a<o;a++){const l=e[a];i[l.uuid]===void 0&&(i[l.uuid]=s.parse(l)),n[l.uuid]=i[l.uuid]}}return n}parseAnimations(e){const t={};if(e!==void 0)for(let i=0;i<e.length;i++){const n=e[i],s=eo.parse(n);t[s.uuid]=s}return t}parseImages(e,t){const i=this,n={};let s;function a(l){return i.manager.itemStart(l),s.load(l,function(){i.manager.itemEnd(l)},void 0,function(){i.manager.itemError(l),i.manager.itemEnd(l)})}function o(l){if(typeof l=="string"){const c=l,h=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(c)?c:i.resourcePath+c;return a(h)}else return l.data?{data:nc(l.type,l.data),width:l.width,height:l.height,complete:!0}:null}if(e!==void 0&&e.length>0){const l=new Pp(t);s=new Gc(l),s.setCrossOrigin(this.crossOrigin);for(let c=0,h=e.length;c<h;c++){const u=e[c],d=u.url;if(Array.isArray(d)){const p=[];for(let m=0,A=d.length;m<A;m++){const g=d[m],y=o(g);y!==null&&(y instanceof HTMLImageElement?p.push(y):p.push(new As(y.data,y.width,y.height)))}n[u.uuid]=new na(p)}else{const p=o(u.url);n[u.uuid]=new na(p)}}}return n}async parseImagesAsync(e){const t=this,i={};let n;async function s(a){if(typeof a=="string"){const o=a,l=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(o)?o:t.resourcePath+o;return await n.loadAsync(l)}else return a.data?{data:nc(a.type,a.data),width:a.width,height:a.height,complete:!0}:null}if(e!==void 0&&e.length>0){n=new Gc(this.manager),n.setCrossOrigin(this.crossOrigin);for(let a=0,o=e.length;a<o;a++){const l=e[a],c=l.url;if(Array.isArray(c)){const h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u],m=await s(p);m!==null&&(m instanceof HTMLImageElement?h.push(m):h.push(new As(m.data,m.width,m.height)))}i[l.uuid]=new na(h)}else{const h=await s(l.url);i[l.uuid]=new na(h)}}}return i}parseTextures(e,t){function i(s,a){return typeof s=="number"?s:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",s),a[s])}const n={};if(e!==void 0)for(let s=0,a=e.length;s<a;s++){const o=e[s];o.image===void 0&&console.warn('THREE.ObjectLoader: No "image" specified for',o.uuid),t[o.image]===void 0&&console.warn("THREE.ObjectLoader: Undefined image",o.image);const l=t[o.image],c=l?l.data:void 0;let h;Array.isArray(c)?(h=new _c,c.length===6&&(h.needsUpdate=!0)):(c&&c.data?h=new As:h=new Rt,c&&c.complete&&(h.needsUpdate=!0)),h.source=l,h.uuid=o.uuid,o.name!==void 0&&(h.name=o.name),o.mapping!==void 0&&(h.mapping=i(o.mapping,EO)),o.channel!==void 0&&(h.channel=o.channel),o.offset!==void 0&&h.offset.fromArray(o.offset),o.repeat!==void 0&&h.repeat.fromArray(o.repeat),o.center!==void 0&&h.center.fromArray(o.center),o.rotation!==void 0&&(h.rotation=o.rotation),o.wrap!==void 0&&(h.wrapS=i(o.wrap[0],px),h.wrapT=i(o.wrap[1],px)),o.format!==void 0&&(h.format=o.format),o.internalFormat!==void 0&&(h.internalFormat=o.internalFormat),o.type!==void 0&&(h.type=o.type),o.colorSpace!==void 0?h.colorSpace=o.colorSpace:o.encoding!==void 0&&(h.encoding=o.encoding),o.minFilter!==void 0&&(h.minFilter=i(o.minFilter,mx)),o.magFilter!==void 0&&(h.magFilter=i(o.magFilter,mx)),o.anisotropy!==void 0&&(h.anisotropy=o.anisotropy),o.flipY!==void 0&&(h.flipY=o.flipY),o.generateMipmaps!==void 0&&(h.generateMipmaps=o.generateMipmaps),o.premultiplyAlpha!==void 0&&(h.premultiplyAlpha=o.premultiplyAlpha),o.unpackAlignment!==void 0&&(h.unpackAlignment=o.unpackAlignment),o.compareFunction!==void 0&&(h.compareFunction=o.compareFunction),o.userData!==void 0&&(h.userData=o.userData),n[o.uuid]=h}return n}parseObject(e,t,i,n,s){let a;const o=e.metadata&&e.metadata.version<=4.5?Dt:void 0;function l(p){return t[p]===void 0&&console.warn("THREE.ObjectLoader: Undefined geometry",p),t[p]}function c(p){if(p!==void 0){if(Array.isArray(p)){const m=[];for(let A=0,g=p.length;A<g;A++){const y=p[A];i[y]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",y),m.push(i[y])}return m}return i[p]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",p),i[p]}}function h(p){return n[p]===void 0&&console.warn("THREE.ObjectLoader: Undefined texture",p),n[p]}let u,d;switch(e.type){case"Scene":a=new qa,e.background!==void 0&&(Number.isInteger(e.background)?a.background=new se().setHex(e.background,o):a.background=h(e.background)),e.environment!==void 0&&(a.environment=h(e.environment)),e.fog!==void 0&&(e.fog.type==="Fog"?a.fog=new $f(e.fog.color,e.fog.near,e.fog.far):e.fog.type==="FogExp2"&&(a.fog=new Yf(e.fog.color,e.fog.density)),e.fog.name!==""&&(a.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(a.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(a.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&a.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(a.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&a.environmentRotation.fromArray(e.environmentRotation);break;case"PerspectiveCamera":a=new Vi(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(a.focus=e.focus),e.zoom!==void 0&&(a.zoom=e.zoom),e.filmGauge!==void 0&&(a.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(a.filmOffset=e.filmOffset),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case"OrthographicCamera":a=new Mr(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(a.zoom=e.zoom),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case"AmbientLight":a=new Rp(e.color,e.intensity);break;case"DirectionalLight":a=new il(e.color,e.intensity);break;case"PointLight":a=new tl(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":a=new Bp(e.color,e.intensity,e.width,e.height);break;case"SpotLight":a=new zc(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay);break;case"HemisphereLight":a=new Dp(e.color,e.groundColor,e.intensity);break;case"LightProbe":a=new fx().fromJSON(e);break;case"SkinnedMesh":u=l(e.geometry),d=c(e.material),a=new np(u,d),e.bindMode!==void 0&&(a.bindMode=e.bindMode),e.bindMatrix!==void 0&&a.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(a.skeleton=e.skeleton);break;case"Mesh":u=l(e.geometry),d=c(e.material),a=new ye(u,d);break;case"InstancedMesh":u=l(e.geometry),d=c(e.material);const p=e.count,m=e.instanceMatrix,A=e.instanceColor;a=new Bc(u,d,p),a.instanceMatrix=new ha(new Float32Array(m.array),16),A!==void 0&&(a.instanceColor=new ha(new Float32Array(A.array),A.itemSize));break;case"BatchedMesh":u=l(e.geometry),d=c(e.material),a=new RC(e.maxGeometryCount,e.maxVertexCount,e.maxIndexCount,d),a.geometry=u,a.perObjectFrustumCulled=e.perObjectFrustumCulled,a.sortObjects=e.sortObjects,a._drawRanges=e.drawRanges,a._reservedRanges=e.reservedRanges,a._visibility=e.visibility,a._active=e.active,a._bounds=e.bounds.map(g=>{const y=new en;y.min.fromArray(g.boxMin),y.max.fromArray(g.boxMax);const _=new un;return _.radius=g.sphereRadius,_.center.fromArray(g.sphereCenter),{boxInitialized:g.boxInitialized,box:y,sphereInitialized:g.sphereInitialized,sphere:_}}),a._maxGeometryCount=e.maxGeometryCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._geometryCount=e.geometryCount,a._matricesTexture=h(e.matricesTexture.uuid);break;case"LOD":a=new bC;break;case"Line":a=new fn(l(e.geometry),c(e.material));break;case"LineLoop":a=new dy(l(e.geometry),c(e.material));break;case"LineSegments":a=new Is(l(e.geometry),c(e.material));break;case"PointCloud":case"Points":a=new jo(l(e.geometry),c(e.material));break;case"Sprite":a=new Zf(c(e.material));break;case"Group":a=new Ri;break;case"Bone":a=new Pc;break;default:a=new ft}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix!==void 0?(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)):(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){const p=e.children;for(let m=0;m<p.length;m++)a.add(this.parseObject(p[m],t,i,n,s))}if(e.animations!==void 0){const p=e.animations;for(let m=0;m<p.length;m++){const A=p[m];a.animations.push(s[A])}}if(e.type==="LOD"){e.autoUpdate!==void 0&&(a.autoUpdate=e.autoUpdate);const p=e.levels;for(let m=0;m<p.length;m++){const A=p[m],g=a.getObjectByProperty("uuid",A.object);g!==void 0&&a.addLevel(g,A.distance,A.hysteresis)}}return a}bindSkeletons(e,t){Object.keys(t).length!==0&&e.traverse(function(i){if(i.isSkinnedMesh===!0&&i.skeleton!==void 0){const n=t[i.skeleton];n===void 0?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",i.skeleton):i.bind(n,i.bindMatrix)}})}}const EO={UVMapping:Kh,CubeReflectionMapping:Kr,CubeRefractionMapping:Io,EquirectangularReflectionMapping:Jr,EquirectangularRefractionMapping:lf,CubeUVReflectionMapping:Yl},px={RepeatWrapping:Bn,ClampToEdgeWrapping:ui,MirroredRepeatWrapping:Zr},mx={NearestFilter:pi,NearestMipmapNearestFilter:Jh,NearestMipmapLinearFilter:Na,LinearFilter:st,LinearMipmapNearestFilter:Po,LinearMipmapLinearFilter:Ln};class gx extends li{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,i,n){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,a=di.get(e);if(a!==void 0){if(s.manager.itemStart(e),a.then){a.then(c=>{t&&t(c),s.manager.itemEnd(e)}).catch(c=>{n&&n(c)});return}return setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return di.add(e,c,"blob"),createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){return di.add(e,c),t&&t(c),s.manager.itemEnd(e),c}).catch(function(c){n&&n(c),di.remove(e),s.manager.itemError(e),s.manager.itemEnd(e)});di.add(e,l),s.manager.itemStart(e)}}let Op;class Oy{static getContext(){return Op===void 0&&(Op=new(window.AudioContext||window.webkitAudioContext)),Op}static setContext(e){Op=e}}class MO extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new Zt(this.manager);a.setResponseType("arraybuffer"),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(l){try{const c=l.slice(0);Oy.getContext().decodeAudioData(c,function(u){t(u)}).catch(o)}catch(c){o(c)}},i,n);function o(l){n?n(l):console.error(l),s.manager.itemError(e)}}}const Ax=new pe,yx=new pe,nl=new pe;class TO{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Vi,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Vi,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,nl.copy(e.projectionMatrix);const n=t.eyeSep/2,s=n*t.near/t.focus,a=t.near*Math.tan(Bo*t.fov*.5)/t.zoom;let o,l;yx.elements[12]=-n,Ax.elements[12]=n,o=-a*t.aspect+s,l=a*t.aspect+s,nl.elements[0]=2*t.near/(l-o),nl.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(nl),o=-a*t.aspect-s,l=a*t.aspect-s,nl.elements[0]=2*t.near/(l-o),nl.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(nl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(yx),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Ax)}}class Lu{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=vx(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=vx();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function vx(){return(typeof performance>"u"?Date:performance).now()}const sl=new x,_x=new Qe,IO=new x,rl=new x;class PO extends ft{constructor(){super(),this.type="AudioListener",this.context=Oy.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Lu}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,i=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(sl,_x,IO),rl.set(0,0,-1).applyQuaternion(_x),t.positionX){const n=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(sl.x,n),t.positionY.linearRampToValueAtTime(sl.y,n),t.positionZ.linearRampToValueAtTime(sl.z,n),t.forwardX.linearRampToValueAtTime(rl.x,n),t.forwardY.linearRampToValueAtTime(rl.y,n),t.forwardZ.linearRampToValueAtTime(rl.z,n),t.upX.linearRampToValueAtTime(i.x,n),t.upY.linearRampToValueAtTime(i.y,n),t.upZ.linearRampToValueAtTime(i.z,n)}else t.setPosition(sl.x,sl.y,sl.z),t.setOrientation(rl.x,rl.y,rl.z,i.x,i.y,i.z)}}class bx extends ft{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].connect(this.filters[e]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].disconnect(this.filters[e]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(e){return e||(e=[]),this._connected===!0?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(e){return this.setFilters(e?[e]:[])}setPlaybackRate(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.playbackRate=e,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1}getLoop(){return this.hasPlaybackControl===!1?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.loop=e,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(e){return this.loopStart=e,this}setLoopEnd(e){return this.loopEnd=e,this}getVolume(){return this.gain.gain.value}setVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}}const al=new x,wx=new Qe,DO=new x,ol=new x;class RO extends bx{constructor(e){super(e),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}connect(){super.connect(),this.panner.connect(this.gain)}disconnect(){super.disconnect(),this.panner.disconnect(this.gain)}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(e){return this.panner.refDistance=e,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(e){return this.panner.rolloffFactor=e,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(e){return this.panner.distanceModel=e,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(e){return this.panner.maxDistance=e,this}setDirectionalCone(e,t,i){return this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=i,this}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(al,wx,DO),ol.set(0,0,1).applyQuaternion(wx);const t=this.panner;if(t.positionX){const i=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(al.x,i),t.positionY.linearRampToValueAtTime(al.y,i),t.positionZ.linearRampToValueAtTime(al.z,i),t.orientationX.linearRampToValueAtTime(ol.x,i),t.orientationY.linearRampToValueAtTime(ol.y,i),t.orientationZ.linearRampToValueAtTime(ol.z,i)}else t.setPosition(al.x,al.y,al.z),t.setOrientation(ol.x,ol.y,ol.z)}}class BO{constructor(e,t=2048){this.analyser=e.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),e.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let e=0;const t=this.getFrequencyData();for(let i=0;i<t.length;i++)e+=t[i];return e/t.length}}class Cx{constructor(e,t,i){this.binding=e,this.valueSize=i;let n,s,a;switch(t){case"quaternion":n=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":n=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:n=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=n,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){const i=this.buffer,n=this.valueSize,s=e*n+n;let a=this.cumulativeWeight;if(a===0){for(let o=0;o!==n;++o)i[s+o]=i[o];a=t}else{a+=t;const o=t/a;this._mixBufferRegion(i,s,0,o,n)}this.cumulativeWeight=a}accumulateAdditive(e){const t=this.buffer,i=this.valueSize,n=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,n,0,e,i),this.cumulativeWeightAdditive+=e}apply(e){const t=this.valueSize,i=this.buffer,n=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){const l=t*this._origIndex;this._mixBufferRegion(i,n,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,n);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,n=i*this._origIndex;e.getValue(t,n);for(let s=i,a=n;s!==a;++s)t[s]=t[n+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i<t;i++)this.buffer[i]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let i=0;i<this.valueSize;i++)this.buffer[t+i]=this.buffer[e+i]}_select(e,t,i,n,s){if(n>=.5)for(let a=0;a!==s;++a)e[t+a]=e[i+a]}_slerp(e,t,i,n){Qe.slerpFlat(e,t,e,t,e,i,n)}_slerpAdditive(e,t,i,n,s){const a=this._workIndex*s;Qe.multiplyQuaternionsFlat(e,a,e,t,e,i),Qe.slerpFlat(e,t,e,t,e,a,n)}_lerp(e,t,i,n,s){const a=1-n;for(let o=0;o!==s;++o){const l=t+o;e[l]=e[l]*a+e[i+o]*n}}_lerpAdditive(e,t,i,n,s){for(let a=0;a!==s;++a){const o=t+a;e[o]=e[o]+e[i+a]*n}}}const Uy="\\[\\]\\.:\\/",LO=new RegExp("["+Uy+"]","g"),Fy="[^"+Uy+"]",OO="[^"+Uy.replace("\\.","")+"]",UO=/((?:WC+[\/:])*)/.source.replace("WC",Fy),FO=/(WCOD+)?/.source.replace("WCOD",OO),NO=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Fy),kO=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Fy),GO=new RegExp("^"+UO+FO+NO+kO+"$"),zO=["material","materials","bones","map"];class VO{constructor(e,t,i){const n=i||Ct.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,n)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,n=this._bindings[i];n!==void 0&&n.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,s=i.length;n!==s;++n)i[n].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class Ct{constructor(e,t,i){this.path=t,this.parsedPath=i||Ct.parseTrackName(t),this.node=Ct.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new Ct.Composite(e,t,i):new Ct(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(LO,"")}static parseTrackName(e){const t=GO.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){const s=i.nodeName.substring(n+1);zO.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(s){for(let a=0;a<s.length;a++){const o=s[a];if(o.name===t||o.uuid===t)return o;const l=i(o.children);if(l)return l}return null},n=i(e.children);if(n)return n}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)e[t++]=i[n]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node;const t=this.parsedPath,i=t.objectName,n=t.propertyName;let s=t.propertyIndex;if(e||(e=Ct.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let c=t.objectIndex;switch(i){case"materials":if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let h=0;h<e.length;h++)if(e[h].name===c){c=h;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[i]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[i]}if(c!==void 0){if(e[c]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}const a=e[n];if(a===void 0){const c=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+c+"."+n+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.needsUpdate!==void 0?o=this.Versioning.NeedsUpdate:e.matrixWorldNeedsUpdate!==void 0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(n==="morphTargetInfluences"){if(!e.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=n;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}Ct.Composite=VO,Ct.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Ct.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Ct.prototype.GetterByBindingType=[Ct.prototype._getValue_direct,Ct.prototype._getValue_array,Ct.prototype._getValue_arrayElement,Ct.prototype._getValue_toArray],Ct.prototype.SetterByBindingTypeAndVersioning=[[Ct.prototype._setValue_direct,Ct.prototype._setValue_direct_setNeedsUpdate,Ct.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ct.prototype._setValue_array,Ct.prototype._setValue_array_setNeedsUpdate,Ct.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ct.prototype._setValue_arrayElement,Ct.prototype._setValue_arrayElement_setNeedsUpdate,Ct.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ct.prototype._setValue_fromArray,Ct.prototype._setValue_fromArray_setNeedsUpdate,Ct.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class HO{constructor(){this.isAnimationObjectGroup=!0,this.uuid=Ss(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const e={};this._indicesByUUID=e;for(let i=0,n=arguments.length;i!==n;++i)e[arguments[i].uuid]=i;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};const t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){const e=this._objects,t=this._indicesByUUID,i=this._paths,n=this._parsedPaths,s=this._bindings,a=s.length;let o,l=e.length,c=this.nCachedObjects_;for(let h=0,u=arguments.length;h!==u;++h){const d=arguments[h],p=d.uuid;let m=t[p];if(m===void 0){m=l++,t[p]=m,e.push(d);for(let A=0,g=a;A!==g;++A)s[A].push(new Ct(d,i[A],n[A]))}else if(m<c){o=e[m];const A=--c,g=e[A];t[g.uuid]=m,e[m]=g,t[p]=A,e[A]=d;for(let y=0,_=a;y!==_;++y){const v=s[y],b=v[A];let T=v[m];v[m]=b,T===void 0&&(T=new Ct(d,i[y],n[y])),v[A]=T}}else e[m]!==o&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=c}remove(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let s=this.nCachedObjects_;for(let a=0,o=arguments.length;a!==o;++a){const l=arguments[a],c=l.uuid,h=t[c];if(h!==void 0&&h>=s){const u=s++,d=e[u];t[d.uuid]=h,e[h]=d,t[c]=u,e[u]=l;for(let p=0,m=n;p!==m;++p){const A=i[p],g=A[u],y=A[h];A[h]=g,A[u]=y}}}this.nCachedObjects_=s}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let s=this.nCachedObjects_,a=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],h=c.uuid,u=t[h];if(u!==void 0)if(delete t[h],u<s){const d=--s,p=e[d],m=--a,A=e[m];t[p.uuid]=u,e[u]=p,t[A.uuid]=d,e[d]=A,e.pop();for(let g=0,y=n;g!==y;++g){const _=i[g],v=_[d],b=_[m];_[u]=v,_[d]=b,_.pop()}}else{const d=--a,p=e[d];d>0&&(t[p.uuid]=u),e[u]=p,e.pop();for(let m=0,A=n;m!==A;++m){const g=i[m];g[u]=g[d],g.pop()}}}this.nCachedObjects_=s}subscribe_(e,t){const i=this._bindingsIndicesByPath;let n=i[e];const s=this._bindings;if(n!==void 0)return s[n];const a=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,h=this.nCachedObjects_,u=new Array(c);n=s.length,i[e]=n,a.push(e),o.push(t),s.push(u);for(let d=h,p=l.length;d!==p;++d){const m=l[d];u[d]=new Ct(m,e,t)}return u}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const n=this._paths,s=this._parsedPaths,a=this._bindings,o=a.length-1,l=a[o],c=e[o];t[c]=i,a[i]=l,a.pop(),s[i]=s[o],s.pop(),n[i]=n[o],n.pop()}}}class xx{constructor(e,t,i=null,n=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=n;const s=t.tracks,a=s.length,o=new Array(a),l={endingStart:Zl,endingEnd:Zl};for(let c=0;c!==a;++c){const h=s[c].createInterpolant(null);o[c]=h,h.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=_A,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i){if(e.fadeOut(t),this.fadeIn(t),i){const n=this._clip.duration,s=e._clip.duration,a=s/n,o=n/s;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const n=this._mixer,s=n.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=n._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=s,l[1]=s+i,c[0]=e/a,c[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,n){if(!this.enabled){this._updateWeight(e);return}const s=this._startTime;if(s!==null){const l=(e-s)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case cw:for(let h=0,u=l.length;h!==u;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);break;case wA:default:for(let h=0,u=l.length;h!==u;++h)l[h].evaluate(a),c[h].accumulate(n,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopFading(),n===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let n=this.time+e,s=this._loopCount;const a=i===DP;if(e===0)return s===-1?n:a&&(s&1)===1?t-n:n;if(i===vA){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(n>=t)n=t;else if(n<0)n=0;else{this.time=n;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),n>=t||n<0){const o=Math.floor(n/t);n-=t*o,s+=Math.abs(o);const l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=e>0?t:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=n;if(a&&(s&1)===1)return t-n}return n}_setEndings(e,t,i){const n=this._interpolantSettings;i?(n.endingStart=ec,n.endingEnd=ec):(e?n.endingStart=this.zeroSlopeAtStart?ec:Zl:n.endingStart=ff,t?n.endingEnd=this.zeroSlopeAtEnd?ec:Zl:n.endingEnd=ff)}_scheduleFading(e,t,i){const n=this._mixer,s=n.time;let a=this._weightInterpolant;a===null&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=i,this}}const QO=new Float32Array(1);class Sx extends wi{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,n=e._clip.tracks,s=n.length,a=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let h=c[l];h===void 0&&(h={},c[l]=h);for(let u=0;u!==s;++u){const d=n[u],p=d.name;let m=h[p];if(m!==void 0)++m.referenceCount,a[u]=m;else{if(m=a[u],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,l,p));continue}const A=t&&t._propertyBindings[u].binding.parsedPath;m=new Cx(Ct.create(i,p,A),d.ValueTypeName,d.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,l,p),a[u]=m}o[u].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,n=e._clip.uuid,s=this._actionsByClip[n];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,n,i)}const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const s=t[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const s=t[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,i){const n=this._actions,s=this._actionsByClip;let a=s[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,s[t]=a;else{const o=a.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=n.length,n.push(e),a.actionByRoot[i]=e}_removeInactiveAction(e){const t=this._actions,i=t[t.length-1],n=e._cacheIndex;i._cacheIndex=n,t[n]=i,t.pop(),e._cacheIndex=null;const s=e._clip.uuid,a=this._actionsByClip,o=a[s],l=o.knownActions,c=l[l.length-1],h=e._byClipCacheIndex;c._byClipCacheIndex=h,l[h]=c,l.pop(),e._byClipCacheIndex=null;const u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],l.length===0&&delete a[s],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const s=t[i];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(e){const t=this._actions,i=e._cacheIndex,n=this._nActiveActions++,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_takeBackAction(e){const t=this._actions,i=e._cacheIndex,n=--this._nActiveActions,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_addInactiveBinding(e,t,i){const n=this._bindingsByRootAndName,s=this._bindings;let a=n[t];a===void 0&&(a={},n[t]=a),a[i]=e,e._cacheIndex=s.length,s.push(e)}_removeInactiveBinding(e){const t=this._bindings,i=e.binding,n=i.rootNode.uuid,s=i.path,a=this._bindingsByRootAndName,o=a[n],l=t[t.length-1],c=e._cacheIndex;l._cacheIndex=c,t[c]=l,t.pop(),delete o[s],Object.keys(o).length===0&&delete a[n]}_lendBinding(e){const t=this._bindings,i=e._cacheIndex,n=this._nActiveBindings++,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_takeBackBinding(e){const t=this._bindings,i=e._cacheIndex,n=--this._nActiveBindings,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let i=e[t];return i===void 0&&(i=new Ey(new Float32Array(2),new Float32Array(2),1,QO),i.__cacheIndex=t,e[t]=i),i}_takeBackControlInterpolant(e){const t=this._controlInterpolants,i=e.__cacheIndex,n=--this._nActiveControlInterpolants,s=t[n];e.__cacheIndex=n,t[n]=e,s.__cacheIndex=i,t[i]=s}clipAction(e,t,i){const n=t||this._root,s=n.uuid;let a=typeof e=="string"?eo.findByName(n,e):e;const o=a!==null?a.uuid:e,l=this._actionsByClip[o];let c=null;if(i===void 0&&(a!==null?i=a.blendMode:i=wA),l!==void 0){const u=l.actionByRoot[s];if(u!==void 0&&u.blendMode===i)return u;c=l.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;const h=new xx(this,a,t,i);return this._bindAction(h,c),this._addInactiveAction(h,o,s),h}existingAction(e,t){const i=t||this._root,n=i.uuid,s=typeof e=="string"?eo.findByName(i,e):e,a=s?s.uuid:e,o=this._actionsByClip[a];return o!==void 0&&o.actionByRoot[n]||null}stopAllAction(){const e=this._actions,t=this._nActiveActions;for(let i=t-1;i>=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,n=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(n,e,s,a);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){const t=this._actions,i=e.uuid,n=this._actionsByClip,s=n[i];if(s!==void 0){const a=s.knownActions;for(let o=0,l=a.length;o!==l;++o){const c=a[o];this._deactivateAction(c);const h=c._cacheIndex,u=t[t.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,u._cacheIndex=h,t[h]=u,t.pop(),this._removeInactiveBindingsForAction(c)}delete n[i]}}uncacheRoot(e){const t=e.uuid,i=this._actionsByClip;for(const a in i){const o=i[a].actionByRoot,l=o[t];l!==void 0&&(this._deactivateAction(l),this._removeInactiveAction(l))}const n=this._bindingsByRootAndName,s=n[t];if(s!==void 0)for(const a in s){const o=s[a];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){const i=this.existingAction(e,t);i!==null&&(this._deactivateAction(i),this._removeInactiveAction(i))}}class Up{constructor(e){this.value=e}clone(){return new Up(this.value.clone===void 0?this.value:this.value.clone())}}let jO=0;class WO extends wi{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:jO++}),this.name="",this.usage=Af,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}setName(e){return this.name=e,this}setUsage(e){return this.usage=e,this}dispose(){return this.dispatchEvent({type:"dispose"}),this}copy(e){this.name=e.name,this.usage=e.usage;const t=e.uniforms;this.uniforms.length=0;for(let i=0,n=t.length;i<n;i++){const s=Array.isArray(t[i])?t[i]:[t[i]];for(let a=0;a<s.length;a++)this.uniforms.push(s[a].clone())}return this}clone(){return new this.constructor().copy(this)}}class Ou extends Sc{constructor(e,t,i=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class qO{constructor(e,t,i,n,s){this.isGLBufferAttribute=!0,this.name="",this.buffer=e,this.type=t,this.itemSize=i,this.elementSize=n,this.count=s,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}}const Ex=new pe;class Uu{constructor(e,t,i=0,n=1/0){this.ray=new Ha(e,t),this.near=i,this.far=n,this.camera=null,this.layers=new If,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error("THREE.Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return Ex.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Ex),this}intersectObject(e,t=!0,i=[]){return Ny(e,this,i,t),i.sort(Mx),i}intersectObjects(e,t=!0,i=[]){for(let n=0,s=e.length;n<s;n++)Ny(e[n],this,i,t);return i.sort(Mx),i}}function Mx(r,e){return r.distance-e.distance}function Ny(r,e,t,i){if(r.layers.test(e.layers)&&r.raycast(e,t),i===!0){const n=r.children;for(let s=0,a=n.length;s<a;s++)Ny(n[s],e,t,!0)}}class pa{constructor(e=1,t=0,i=0){return this.radius=e,this.phi=t,this.theta=i,this}set(e,t,i){return this.radius=e,this.phi=t,this.theta=i,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Math.max(1e-6,Math.min(Math.PI-1e-6,this.phi)),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+t*t+i*i),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(zi(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}class XO{constructor(e=1,t=0,i=0){return this.radius=e,this.theta=t,this.y=i,this}set(e,t,i){return this.radius=e,this.theta=t,this.y=i,this}copy(e){return this.radius=e.radius,this.theta=e.theta,this.y=e.y,this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+i*i),this.theta=Math.atan2(e,i),this.y=t,this}clone(){return new this.constructor().copy(this)}}class Fp{constructor(e,t,i,n){Fp.prototype.isMatrix2=!0,this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,n){const s=this.elements;return s[0]=e,s[2]=t,s[1]=i,s[3]=n,this}}const Tx=new $;class ky{constructor(e=new $(1/0,1/0),t=new $(-1/0,-1/0)){this.isBox2=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=Tx.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(e){return this.isEmpty()?e.set(0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}containsPoint(e){return!(e.x<this.min.x||e.x>this.max.x||e.y<this.min.y||e.y>this.max.y)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return!(e.max.x<this.min.x||e.min.x>this.max.x||e.max.y<this.min.y||e.min.y>this.max.y)}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Tx).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const Ix=new x,Np=new x;class Gy{constructor(e=new x,t=new x){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Ix.subVectors(e,this.start),Np.subVectors(this.end,this.start);const i=Np.dot(Np);let s=Np.dot(Ix)/i;return t&&(s=zi(s,0,1)),s}closestPointToPoint(e,t,i){const n=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(n).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const Px=new x;class YO extends ft{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new $e,n=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let a=0,o=1,l=32;a<l;a++,o++){const c=a/l*Math.PI*2,h=o/l*Math.PI*2;n.push(Math.cos(c),Math.sin(c),1,Math.cos(h),Math.sin(h),1)}i.setAttribute("position",new Me(n,3));const s=new Ei({fog:!1,toneMapped:!1});this.cone=new Is(i,s),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);const e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),Px.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Px),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}const no=new x,kp=new pe,zy=new pe;class $O extends Is{constructor(e){const t=Dx(e),i=new $e,n=[],s=[],a=new se(0,0,1),o=new se(0,1,0);for(let c=0;c<t.length;c++){const h=t[c];h.parent&&h.parent.isBone&&(n.push(0,0,0),n.push(0,0,0),s.push(a.r,a.g,a.b),s.push(o.r,o.g,o.b))}i.setAttribute("position",new Me(n,3)),i.setAttribute("color",new Me(s,3));const l=new Ei({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(i,l),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(e){const t=this.bones,i=this.geometry,n=i.getAttribute("position");zy.copy(this.root.matrixWorld).invert();for(let s=0,a=0;s<t.length;s++){const o=t[s];o.parent&&o.parent.isBone&&(kp.multiplyMatrices(zy,o.matrixWorld),no.setFromMatrixPosition(kp),n.setXYZ(a,no.x,no.y,no.z),kp.multiplyMatrices(zy,o.parent.matrixWorld),no.setFromMatrixPosition(kp),n.setXYZ(a+1,no.x,no.y,no.z),a+=2)}i.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}}function Dx(r){const e=[];r.isBone===!0&&e.push(r);for(let t=0;t<r.children.length;t++)e.push.apply(e,Dx(r.children[t]));return e}class KO extends ye{constructor(e,t,i){const n=new Ds(t,4,2),s=new ss({wireframe:!0,fog:!1,toneMapped:!1});super(n,s),this.light=e,this.color=i,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.color!==void 0?this.material.color.set(this.color):this.material.color.copy(this.light.color)}}const JO=new x,Rx=new se,Bx=new se;class ZO extends ft{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="HemisphereLightHelper";const n=new da(t);n.rotateY(Math.PI*.5),this.material=new ss({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);const s=n.getAttribute("position"),a=new Float32Array(s.count*3);n.setAttribute("color",new Xe(a,3)),this.add(new ye(n,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const e=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{const t=e.geometry.getAttribute("color");Rx.copy(this.light.color),Bx.copy(this.light.groundColor);for(let i=0,n=t.count;i<n;i++){const s=i<n/2?Rx:Bx;t.setXYZ(i,s.r,s.g,s.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(JO.setFromMatrixPosition(this.light.matrixWorld).negate())}}class eU extends Is{constructor(e=10,t=10,i=4473924,n=8947848){i=new se(i),n=new se(n);const s=t/2,a=e/t,o=e/2,l=[],c=[];for(let d=0,p=0,m=-o;d<=t;d++,m+=a){l.push(-o,0,m,o,0,m),l.push(m,0,-o,m,0,o);const A=d===s?i:n;A.toArray(c,p),p+=3,A.toArray(c,p),p+=3,A.toArray(c,p),p+=3,A.toArray(c,p),p+=3}const h=new $e;h.setAttribute("position",new Me(l,3)),h.setAttribute("color",new Me(c,3));const u=new Ei({vertexColors:!0,toneMapped:!1});super(h,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class tU extends Is{constructor(e=10,t=16,i=8,n=64,s=4473924,a=8947848){s=new se(s),a=new se(a);const o=[],l=[];if(t>1)for(let u=0;u<t;u++){const d=u/t*(Math.PI*2),p=Math.sin(d)*e,m=Math.cos(d)*e;o.push(0,0,0),o.push(p,0,m);const A=u&1?s:a;l.push(A.r,A.g,A.b),l.push(A.r,A.g,A.b)}for(let u=0;u<i;u++){const d=u&1?s:a,p=e-e/i*u;for(let m=0;m<n;m++){let A=m/n*(Math.PI*2),g=Math.sin(A)*p,y=Math.cos(A)*p;o.push(g,0,y),l.push(d.r,d.g,d.b),A=(m+1)/n*(Math.PI*2),g=Math.sin(A)*p,y=Math.cos(A)*p,o.push(g,0,y),l.push(d.r,d.g,d.b)}}const c=new $e;c.setAttribute("position",new Me(o,3)),c.setAttribute("color",new Me(l,3));const h=new Ei({vertexColors:!0,toneMapped:!1});super(c,h),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}const Lx=new x,Gp=new x,Ox=new x;class iU extends ft{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="DirectionalLightHelper",t===void 0&&(t=1);let n=new $e;n.setAttribute("position",new Me([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));const s=new Ei({fog:!1,toneMapped:!1});this.lightPlane=new fn(n,s),this.add(this.lightPlane),n=new $e,n.setAttribute("position",new Me([0,0,0,0,0,1],3)),this.targetLine=new fn(n,s),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),Lx.setFromMatrixPosition(this.light.matrixWorld),Gp.setFromMatrixPosition(this.light.target.matrixWorld),Ox.subVectors(Gp,Lx),this.lightPlane.lookAt(Gp),this.color!==void 0?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(Gp),this.targetLine.scale.z=Ox.length()}}const zp=new x,Hi=new Ac;class nU extends Is{constructor(e){const t=new $e,i=new Ei({color:16777215,vertexColors:!0,toneMapped:!1}),n=[],s=[],a={};o("n1","n2"),o("n2","n4"),o("n4","n3"),o("n3","n1"),o("f1","f2"),o("f2","f4"),o("f4","f3"),o("f3","f1"),o("n1","f1"),o("n2","f2"),o("n3","f3"),o("n4","f4"),o("p","n1"),o("p","n2"),o("p","n3"),o("p","n4"),o("u1","u2"),o("u2","u3"),o("u3","u1"),o("c","t"),o("p","c"),o("cn1","cn2"),o("cn3","cn4"),o("cf1","cf2"),o("cf3","cf4");function o(m,A){l(m),l(A)}function l(m){n.push(0,0,0),s.push(0,0,0),a[m]===void 0&&(a[m]=[]),a[m].push(n.length/3-1)}t.setAttribute("position",new Me(n,3)),t.setAttribute("color",new Me(s,3)),super(t,i),this.type="CameraHelper",this.camera=e,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=a,this.update();const c=new se(16755200),h=new se(16711680),u=new se(43775),d=new se(16777215),p=new se(3355443);this.setColors(c,h,u,d,p)}setColors(e,t,i,n,s){const o=this.geometry.getAttribute("color");o.setXYZ(0,e.r,e.g,e.b),o.setXYZ(1,e.r,e.g,e.b),o.setXYZ(2,e.r,e.g,e.b),o.setXYZ(3,e.r,e.g,e.b),o.setXYZ(4,e.r,e.g,e.b),o.setXYZ(5,e.r,e.g,e.b),o.setXYZ(6,e.r,e.g,e.b),o.setXYZ(7,e.r,e.g,e.b),o.setXYZ(8,e.r,e.g,e.b),o.setXYZ(9,e.r,e.g,e.b),o.setXYZ(10,e.r,e.g,e.b),o.setXYZ(11,e.r,e.g,e.b),o.setXYZ(12,e.r,e.g,e.b),o.setXYZ(13,e.r,e.g,e.b),o.setXYZ(14,e.r,e.g,e.b),o.setXYZ(15,e.r,e.g,e.b),o.setXYZ(16,e.r,e.g,e.b),o.setXYZ(17,e.r,e.g,e.b),o.setXYZ(18,e.r,e.g,e.b),o.setXYZ(19,e.r,e.g,e.b),o.setXYZ(20,e.r,e.g,e.b),o.setXYZ(21,e.r,e.g,e.b),o.setXYZ(22,e.r,e.g,e.b),o.setXYZ(23,e.r,e.g,e.b),o.setXYZ(24,t.r,t.g,t.b),o.setXYZ(25,t.r,t.g,t.b),o.setXYZ(26,t.r,t.g,t.b),o.setXYZ(27,t.r,t.g,t.b),o.setXYZ(28,t.r,t.g,t.b),o.setXYZ(29,t.r,t.g,t.b),o.setXYZ(30,t.r,t.g,t.b),o.setXYZ(31,t.r,t.g,t.b),o.setXYZ(32,i.r,i.g,i.b),o.setXYZ(33,i.r,i.g,i.b),o.setXYZ(34,i.r,i.g,i.b),o.setXYZ(35,i.r,i.g,i.b),o.setXYZ(36,i.r,i.g,i.b),o.setXYZ(37,i.r,i.g,i.b),o.setXYZ(38,n.r,n.g,n.b),o.setXYZ(39,n.r,n.g,n.b),o.setXYZ(40,s.r,s.g,s.b),o.setXYZ(41,s.r,s.g,s.b),o.setXYZ(42,s.r,s.g,s.b),o.setXYZ(43,s.r,s.g,s.b),o.setXYZ(44,s.r,s.g,s.b),o.setXYZ(45,s.r,s.g,s.b),o.setXYZ(46,s.r,s.g,s.b),o.setXYZ(47,s.r,s.g,s.b),o.setXYZ(48,s.r,s.g,s.b),o.setXYZ(49,s.r,s.g,s.b),o.needsUpdate=!0}update(){const e=this.geometry,t=this.pointMap,i=1,n=1;Hi.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),rn("c",t,e,Hi,0,0,-1),rn("t",t,e,Hi,0,0,1),rn("n1",t,e,Hi,-i,-n,-1),rn("n2",t,e,Hi,i,-n,-1),rn("n3",t,e,Hi,-i,n,-1),rn("n4",t,e,Hi,i,n,-1),rn("f1",t,e,Hi,-i,-n,1),rn("f2",t,e,Hi,i,-n,1),rn("f3",t,e,Hi,-i,n,1),rn("f4",t,e,Hi,i,n,1),rn("u1",t,e,Hi,i*.7,n*1.1,-1),rn("u2",t,e,Hi,-i*.7,n*1.1,-1),rn("u3",t,e,Hi,0,n*2,-1),rn("cf1",t,e,Hi,-i,0,1),rn("cf2",t,e,Hi,i,0,1),rn("cf3",t,e,Hi,0,-n,1),rn("cf4",t,e,Hi,0,n,1),rn("cn1",t,e,Hi,-i,0,-1),rn("cn2",t,e,Hi,i,0,-1),rn("cn3",t,e,Hi,0,-n,-1),rn("cn4",t,e,Hi,0,n,-1),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}}function rn(r,e,t,i,n,s,a){zp.set(n,s,a).unproject(i);const o=e[r];if(o!==void 0){const l=t.getAttribute("position");for(let c=0,h=o.length;c<h;c++)l.setXYZ(o[c],zp.x,zp.y,zp.z)}}const Vp=new en;class sU extends Is{constructor(e,t=16776960){const i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),n=new Float32Array(24),s=new $e;s.setIndex(new Xe(i,1)),s.setAttribute("position",new Xe(n,3)),super(s,new Ei({color:t,toneMapped:!1})),this.object=e,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(e){if(e!==void 0&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),this.object!==void 0&&Vp.setFromObject(this.object),Vp.isEmpty())return;const t=Vp.min,i=Vp.max,n=this.geometry.attributes.position,s=n.array;s[0]=i.x,s[1]=i.y,s[2]=i.z,s[3]=t.x,s[4]=i.y,s[5]=i.z,s[6]=t.x,s[7]=t.y,s[8]=i.z,s[9]=i.x,s[10]=t.y,s[11]=i.z,s[12]=i.x,s[13]=i.y,s[14]=t.z,s[15]=t.x,s[16]=i.y,s[17]=t.z,s[18]=t.x,s[19]=t.y,s[20]=t.z,s[21]=i.x,s[22]=t.y,s[23]=t.z,n.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class rU extends Is{constructor(e,t=16776960){const i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),n=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],s=new $e;s.setIndex(new Xe(i,1)),s.setAttribute("position",new Me(n,3)),super(s,new Ei({color:t,toneMapped:!1})),this.box=e,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(e){const t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(e))}dispose(){this.geometry.dispose(),this.material.dispose()}}class aU extends fn{constructor(e,t=1,i=16776960){const n=i,s=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],a=new $e;a.setAttribute("position",new Me(s,3)),a.computeBoundingSphere(),super(a,new Ei({color:n,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;const o=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],l=new $e;l.setAttribute("position",new Me(o,3)),l.computeBoundingSphere(),this.add(new ye(l,new ss({color:n,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(e){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const Ux=new x;let Hp,Vy;class oU extends ft{constructor(e=new x(0,0,1),t=new x(0,0,0),i=1,n=16776960,s=i*.2,a=s*.2){super(),this.type="ArrowHelper",Hp===void 0&&(Hp=new $e,Hp.setAttribute("position",new Me([0,0,0,0,1,0],3)),Vy=new sn(0,.5,1,5,1),Vy.translate(0,-.5,0)),this.position.copy(t),this.line=new fn(Hp,new Ei({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new ye(Vy,new ss({color:n,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(i,s,a)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Ux.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Ux,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class lU extends Is{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],n=new $e;n.setAttribute("position",new Me(t,3)),n.setAttribute("color",new Me(i,3));const s=new Ei({vertexColors:!0,toneMapped:!1});super(n,s),this.type="AxesHelper"}setColors(e,t,i){const n=new se,s=this.geometry.attributes.color.array;return n.set(e),n.toArray(s,0),n.toArray(s,3),n.set(t),n.toArray(s,6),n.toArray(s,9),n.set(i),n.toArray(s,12),n.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class cU{constructor(){this.type="ShapePath",this.color=new se,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Uc,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,n){return this.currentPath.quadraticCurveTo(e,t,i,n),this}bezierCurveTo(e,t,i,n,s,a){return this.currentPath.bezierCurveTo(e,t,i,n,s,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(y){const _=[];for(let v=0,b=y.length;v<b;v++){const T=y[v],E=new ar;E.curves=T.curves,_.push(E)}return _}function i(y,_){const v=_.length;let b=!1;for(let T=v-1,E=0;E<v;T=E++){let M=_[T],S=_[E],w=S.x-M.x,C=S.y-M.y;if(Math.abs(C)>Number.EPSILON){if(C<0&&(M=_[E],w=-w,S=_[T],C=-C),y.y<M.y||y.y>S.y)continue;if(y.y===M.y){if(y.x===M.x)return!0}else{const D=C*(y.x-M.x)-w*(y.y-M.y);if(D===0)return!0;if(D<0)continue;b=!b}}else{if(y.y!==M.y)continue;if(S.x<=y.x&&y.x<=M.x||M.x<=y.x&&y.x<=S.x)return!0}}return b}const n=or.isClockWise,s=this.subPaths;if(s.length===0)return[];let a,o,l;const c=[];if(s.length===1)return o=s[0],l=new ar,l.curves=o.curves,c.push(l),c;let h=!n(s[0].getPoints());h=e?!h:h;const u=[],d=[];let p=[],m=0,A;d[m]=void 0,p[m]=[];for(let y=0,_=s.length;y<_;y++)o=s[y],A=o.getPoints(),a=n(A),a=e?!a:a,a?(!h&&d[m]&&m++,d[m]={s:new ar,p:A},d[m].s.curves=o.curves,h&&m++,p[m]=[]):p[m].push({h:o,p:A[0]});if(!d[0])return t(s);if(d.length>1){let y=!1,_=0;for(let v=0,b=d.length;v<b;v++)u[v]=[];for(let v=0,b=d.length;v<b;v++){const T=p[v];for(let E=0;E<T.length;E++){const M=T[E];let S=!0;for(let w=0;w<d.length;w++)i(M.p,d[w].p)&&(v!==w&&_++,S?(S=!1,u[w].push(M)):y=!0);S&&u[v].push(M)}}_>0&&y===!1&&(p=u)}let g;for(let y=0,_=d.length;y<_;y++){l=d[y].s,c.push(l),g=p[y];for(let v=0,b=g.length;v<b;v++)l.holes.push(g[v].h)}return c}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"163"}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="163");/**
 * @license
 * ts-browser-helpers v0.19.4
 * Copyright 2022-2025 repalash <palash@shaders.app>
 * MIT License
 * See ./dependencies.txt for bundled third-party dependencies and licenses.
 */let Qp=class{constructor(){this._eventListeners={},this.dispatchEvent=this.dispatchEvent.bind(this),this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.hasEventListener=this.hasEventListener.bind(this)}addEventListener(e,t){const i=this._eventListeners;i[e]===void 0&&(i[e]=[]),i[e].includes(t)||i[e].push(t)}hasEventListener(e,t){const i=this._eventListeners;return i[e]!==void 0&&i[e].includes(t)}removeEventListener(e,t){const i=this._eventListeners[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._eventListeners[e.type];if(t!==void 0){e.target=this;const i=t.slice(0);for(let n=0,s=i.length;n<s;n++)i[n].call(this,e)}}};async function jn(r){return new Promise(e=>setTimeout(e,Math.max(0,r)))}function Mn(){return(typeof performance>"u"?Date:performance).now()}class Fx extends Qp{constructor(){super(...arguments),this._onPointerDown=e=>{if(e.button!==0||!this._element)return;this._pointerUp=void 0;const t=e.clientX/this._element.clientWidth*2-1,i=-(e.clientY/this._element.clientHeight)*2+1,n=Mn();this._pointerDown={x:t,y:i,time:n},this._pointer=this._pointerDown,this.dispatchEvent({type:"dragStart",pointer:this._pointerDown})},this._onPointerMove=e=>{if(!this._pointerDown||!this._pointer||!this._element)return;const t=e.clientX/this._element.clientWidth*2-1,i=-(e.clientY/this._element.clientHeight)*2+1,n=Mn();this.dispatchEvent({type:"drag",pointer:this._pointer,drag:{x:t-this._pointerDown.x,y:i-this._pointerDown.y,time:n-this._pointerDown.time},delta:{x:t-this._pointer.x,y:i-this._pointer.y,time:n-this._pointer.time}}),this._pointer={x:t,y:i,time:Mn()},e.buttons%2===0&&this._onPointerUp(e)},this._onPointerUp=e=>{if(e.button!==0||!this._pointerDown||!this._element)return;const t=e.clientX/this._element.clientWidth*2-1,i=-(e.clientY/this._element.clientHeight)*2+1,n=Mn();this._pointerUp={x:t,y:i,time:n},this.dispatchEvent({type:"dragEnd",pointer:this._pointerUp,drag:{x:this._pointerUp.x-this._pointerDown.x,y:this._pointerUp.y-this._pointerDown.y,time:this._pointerUp.time-this._pointerDown.time}}),this._pointerDown=void 0,this._pointer=void 0}}get element(){return this._element}set element(e){this._element!==e&&(this._element&&this._removeElement(),this._element=e,this._element&&this._addElement())}_removeElement(){var e,t,i,n,s;(e=this._element)==null||e.removeEventListener("pointerdown",this._onPointerDown),(t=this._element)==null||t.removeEventListener("pointermove",this._onPointerMove),(i=this._element)==null||i.removeEventListener("pointerup",this._onPointerUp),(n=this._element)==null||n.removeEventListener("pointercancel",this._onPointerUp),(s=this._element)==null||s.removeEventListener("pointerout",this._onPointerUp)}_addElement(){var e,t,i,n,s;(e=this._element)==null||e.addEventListener("pointerdown",this._onPointerDown),(t=this._element)==null||t.addEventListener("pointermove",this._onPointerMove),(i=this._element)==null||i.addEventListener("pointerup",this._onPointerUp),(n=this._element)==null||n.addEventListener("pointercancel",this._onPointerUp),(s=this._element)==null||s.addEventListener("pointerout",this._onPointerUp)}dispose(){this.element=void 0}}class Hy{constructor(e){this.options={limit:500,debug:!1,bindHotKeys:!1},this.enabled=!0,this.presets={},this._keyDown=t=>{if(!this.enabled)return;const i=t.ctrlKey||t.metaKey;t.code==="KeyZ"&&i&&!t.shiftKey?this.undo():(t.code==="KeyZ"&&i&&t.shiftKey||t.code==="KeyY"&&t.ctrlKey)&&this.redo()},Object.assign(this.options,e),this.limit=e.limit,this.options=e,this.reset(),e.bindHotKeys&&this.bindHotKeys(),this.log(`Initialized with stack limit of ${this.limit} commands`)}bindHotKeys(){return this.log("Bound 'undo' and 'redo' actions to 'Ctrl/Cmd+Z', 'Ctrl+Y' & 'Ctrl/Cmd+Shift+Z' hot keys"),(this.options.hotKeyRoot??document).addEventListener("keydown",this._keyDown),this}dispose(){return(this.options.hotKeyRoot??document).removeEventListener("keydown",this._keyDown),this.reset()}record(e){return this.enabled?(this._record(e),this):this}replaceLast(e){const t=this.peek();if(t)return this.log("replace",t,"with",e),this.stack[this.sp]=e,this}execute(e){if(!this.enabled)return;let t=this._rc(e),i=t.redo;return this.record.apply(this,t),this.log("Executing function..."),i.apply(e),this}_rc(e){if(e.type){const t=this.presets[e.type];if(typeof t=="function")return t(e);throw console.error(e,t,this.presets),new Error("Preset command not found")}else return e}_record(e){this.enabled&&(this.log("Recording command",e),this._rebase(),this.stack.push(e),this.sp++,this._keepLimit())}_rebase(){this.canRedo()&&(this.stack.length=this.sp+1)}_keepLimit(){if(this.stack.length<=this.limit)return;let e=this.stack.length-this.limit;this.log("Stack size reached its limit: ${this.limit} commands. Cutting off most old commands..."),e===1?this.stack.shift():this.stack.splice(0,e),this.sp-=e}undo(){if(!this.canUndo())return this;let e=this.stack[this.sp];return this.log("undo"),this.sp--,this._rc(e).undo(),this}canUndo(){return this.sp>=0&&this.enabled}peek(){return this.canUndo()?this.stack[this.sp]:null}redo(){if(!this.canRedo())return this;let e=this.stack[this.sp+1];return this.log("redo"),this.sp++,this._rc(e).redo(),this}canRedo(){return this.sp<this.stack.length-1&&this.enabled}peekForward(){return this.canRedo()?this.stack[this.sp+1]:null}setLimit(e){let t=this.stack.length-this.sp-1;if(e<1||typeof e!="number")throw new TypeError(`JSUndoManager.setLimit(): unexpected argument limit=${e}. Should be a positive number`);return e<t?console.warn(`JSUndoManager.setLimit(): cannot set stack limit (${e}) less than the number of 'redoable' commands (${t})`):(this.limit=Math.floor(e),this._keepLimit()),this}reset(){return this.log("reset"),this.stack=[],this.sp=-1,this}isEmpty(){return!this.stack.length}isFull(){return this.stack.length===this.limit}getSize(){return this.stack.length}log(e,...t){this.options.debug&&console.log(`Command Manager: ${e}`,...t)}}/* @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const jp=class yb{constructor(e=yb.DECAY_MILLISECONDS){this.velocity=0,this.naturalFrequency=0,this.setDecayTime(e)}setDecayTime(e){this.naturalFrequency=1/Math.max(yb.MIN_DECAY_MILLISECONDS,e)}update(e,t,i,n){const s=2e-4*this.naturalFrequency;if(e==null||n===0||e===t&&this.velocity===0)return t;if(i<0)return e;const a=e-t,o=this.velocity+this.naturalFrequency*a,l=a+i*o,c=Math.exp(-this.naturalFrequency*i),h=(o-this.naturalFrequency*l)*c,u=-this.naturalFrequency*(h+o*c);return Math.abs(h)<s*Math.abs(n)&&u*a>=0?(this.velocity=0,t):(this.velocity=h,t+l*c)}};jp.SETTLING_TIME=1e4,jp.MIN_DECAY_MILLISECONDS=.001,jp.DECAY_MILLISECONDS=50;let hU=jp;function Nx(){const r=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");return r.style.display="block",r}function Pr({innerHTML:r="",id:e,classList:t,addToBody:i=!0,elementTag:n="div"}){const s=document.createElement(n);return e&&(s.id=e),s.innerHTML=r,t&&s.classList.add(...t),i&&document.body.appendChild(s),s}async function kx(r){return new Promise((e,t)=>{const i=new Image;i.onload=()=>e(i),i.onerror=t,i.crossOrigin="anonymous",i.decoding="sync",i.src=r})}function ll(r,e=document.head){const t=document.createElement("style");return t.type="text/css",t.innerText=r,e?.appendChild(t),t}async function uU(r,e=document.head){return new Promise((t,i)=>{const n=document.createElement("script");n.setAttribute("src",r),n.addEventListener("load",()=>t(n)),n.addEventListener("error",i),e.appendChild(n)})}async function dU(r,e){var t;r.innerHTML=e;const i=r.getElementsByTagName("script");for(let n=0;n<i.length;n++){const s=i[n],a=Gx(s);let o=!1;await new Promise(l=>{a.onload=l,a.onerror=()=>{o=!0,l(void 0)}}),!o&&((t=s.parentNode)==null||t.replaceChild(a,s))}}function Gx(r,e){e=e??document.createElement("script"),e.type=r.type||"text/javascript",e.text=r.text;for(let t=0;t<r.attributes.length;t++){const i=r.attributes[t];e.setAttribute(i.name,i.value)}return e}function Wp(r){if(!window)return console.warn("window is required"),"";let e="";const t=new Uint8Array(r),i=t.byteLength;for(let n=0;n<i;n++)e+=String.fromCharCode(t[n]);return window.btoa(e)}function Qy(r){if(!window)return console.warn("window is required"),new Uint8Array(0);const e=window.atob(r),t=e.length,i=new Uint8Array(t);for(let n=0;n<t;n++)i[n]=e.charCodeAt(n);return i.buffer}const zx={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Vx(r,e){return new zx[r](e)}function Hx(r){return r.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function fU(r){return r.replace(/([-_][a-z])/ig,e=>e.toUpperCase().replace("-","").replace("_",""))}function Fu(r){if(!r||r===""||r.match(/__MACOSX\/.*\._/))return"";r=r.replace(/\?.*$/,"");const e=r.split(/[\\/]/).pop()??"",t=e.lastIndexOf(".");return e===""||t<1?"":e.slice(t+1)}function pU(r){return r.substring(r.lastIndexOf("/")+1)}function Nu(r){return RegExp.escape?RegExp.escape(r):r.replace(/[.*+?^${}()|[\]/\\=!:]/g,"\\$&")}function Wn(r,e,t){return r.replace(new RegExp(Nu(e),"g"),t)}function mU(r,e,t,{replaceAll:i=!1,prepend:n=!1,append:s=!1,notFoundCallback:a=()=>{}}={}){if(a&&!r.includes(e))return a(),r;let o=t;return n?o=t+e:s&&(o=e+t),i?r.replaceAll(e,o):r.replace(e,o)}function gU(r){return r.sort(),r[0].split("").map((e,t)=>r[r.length-1][t]===e?e:"\0").join("").split("\0").at(0)||""}function Vs(r){return r.replace(/[&<>"']/g,function(e){switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return e}})}const ma=(r,...e)=>String.raw({raw:r},...e),Qx=(r,...e)=>String.raw({raw:r},...e),AU=(r,...e)=>String.raw({raw:r},...e),jy=(r,...e)=>{let t=String.raw({raw:r},...e);return t=Wn(t,"%","%25"),t=Wn(t,"> <","><"),t=Wn(t,"; }",";}"),t=Wn(t,"<","%3c"),t=Wn(t,">","%3e"),t=Wn(t,'"',"'"),t=Wn(t,"#","%23"),t=Wn(t,"{","%7b"),t=Wn(t,"}","%7d"),t=Wn(t,"|","%7c"),t=Wn(t,"^","%5e"),t=Wn(t,"`","%60"),t=Wn(t,"@","%40"),t=Wn(t,"&","&amp;"),t=Wn(t,`
`,"%0A"),"data:image/svg+xml;charset=UTF-8,"+t};function yU(r=document.head){return ll(Qx`
      ::-webkit-scrollbar
      {
        width: 8px;  /* for vertical scrollbars */
        height: 8px; /* for horizontal scrollbars */
      }
      ::-webkit-scrollbar-track
      {
        background: rgba(64, 64, 64, 0.4);
        border-radius: 6px;
      }
      ::-webkit-scrollbar-thumb
      {
        background: rgba(128, 128, 128, 0.2);
        border-radius: 6px;
      }
      ::-webkit-scrollbar-corner {background: rgba(0,0,0,0.5);}
    `,r)}function ku(r,e){const t=window.URL.createObjectURL(r),i=document.createElement("a");i.style.display="none",i.href=t,i.download=e,document.body.appendChild(i),i.click(),setTimeout(()=>{document.body.removeChild(i),window.URL.revokeObjectURL(t)},1e3)}async function qp(r){return new Promise((e,t)=>{const i=new FileReader;i.onload=n=>e(i.result),i.onerror=n=>t(i.error),i.onabort=n=>t(new Error("Read aborted")),i.readAsDataURL(r)})}function jx(r,e){return ku(r,e??r.name)}async function Wx(r=!1,e=!1,t){const i=document.createElement("input");i.type="file",i.multiple=r,i.accept=t||"*",i.webkitdirectory=e,i.style.display="none",document.body.appendChild(i),i.click();const n=await new Promise(s=>{i.onchange=a=>{s(Array.from(i.files||[]))}});return document.body.removeChild(i),n}function vU(){let r=!1;return(function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(r=!0)})(navigator.userAgent||navigator.vendor||window.opera),r}function _U(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function qx(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}function bU(r,e=1,t=1){const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");n.fillStyle="#"+r,n.fillRect(0,0,e,t);const s=i.toDataURL();return i.remove(),s}function Xx(r,e){let t;do t=Object.getOwnPropertyDescriptor(r,e);while(!t&&(r=Object.getPrototypeOf(r)));return t}function Yx(r,e,t=!0,i=!1){const n=Xx(r,e);return!!(n!=null&&n.set)||t&&n?.writable!==!1&&n?.get===void 0||i&&!n}function an(r,e,t,i=!0,n=!1){return r&&Yx(r,e,i,n)?(r[e]=t,!0):!1}function it(r,...e){return typeof r=="function"&&(r=r(...e)),r}function $x(r,e,t){for(const i of t){const n=r[i];n!==void 0&&an(e,i,n,!0)}return e}function Kx(r,e){for(const t of e)if(!r.includes(t))return!1;return!0}function Jx(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}function wU(r,e){return function(...t){return r(),e&&e.call(this,...t)}}function Zx(r,e){return function(...t){return r(...t),e&&e.call(this,...t)}}function Gu(r,e,t=!1){for(typeof r=="string"&&(r=r.split("."));r.length>0;){if(!e)return e;const i=r.splice(0,1)[0];if(!(i.length<1))if(Array.isArray(e))e=e[parseInt(i)];else if(typeof e=="object"&&i in e)e=e[i];else{if(t)throw new Error("invalid access, check "+i+" in "+e);return}}return e}function CU(r,e){return Object.keys(r).find(t=>r[t]===e)}function qn(r,e){return Object.hasOwn?Object.hasOwn(r,e):r.hasOwnProperty(e)}function eS(r,e,t=!0){const i=t?r:{},n=Object.keys(r);for(const s of n)i[s]=e(r[s],s);return i}function Wy(r,e){return Object.fromEntries(Object.entries(r).map(t=>e(t)))}const qy={priority:1/0,serialize:(r,e)=>Wy(r,([t,i])=>[t,Bt.Serialize(i,e,!1)]),deserialize:(r,e,t)=>Object.assign(e||{},Wy(r,([i,n])=>[i,Bt.Deserialize(n,e?.[i],t,!1)])),isType:r=>(r.constructor||Object)===Object},cl=class xs{static GetSerializer(e){return xs.Serializers.find(t=>t.isType(e))}static RegisterSerializer(...e){for(const t of e){const i=t.priority??1e10,n=Jx(xs.Serializers,s=>s.priority!==void 0&&s.priority<i);n>=0?xs.Serializers.splice(n+1,0,t):xs.Serializers.push(t)}}static UnregisterSerializer(...e){for(const t of e){const i=xs.Serializers.indexOf(t);i>=0&&xs.Serializers.splice(i,1)}}static Serialize(e,t,i=!1){if(typeof e=="function")return;if(!i){const a=xs.GetSerializer(e);if(a)return a.serialize(e,t);if(typeof e.toJSON=="function"){const o=e.toJSON(t,!0);return e.serializableClassId&&o&&(o.serializableClassId=e.serializableClassId),o}}let n=e.constructor??Object;const s={};for(;n&&n!==Object;){const a=xs.TypeMap.get(n)??[];for(const[o,l]of a)s[o]=xs.Serialize(e[l],t,!1);n=Object.getPrototypeOf(n)}return e.serializableClassId&&(s.serializableClassId=e.serializableClassId),s}static Deserialize(e,t,i,n=!1){if(e===void 0||t===e)return t;if(e&&typeof e=="object"&&(e.constructor||Object)===Object&&e.resource&&typeof e.resource=="string"&&e.uuid){const a=i?.[e.resource];if(!a)return console.warn(`Serialization: Resource ${e.resource} not found`),t;const o=a[e.uuid];if(!o)return console.warn(`Serialization: Resource ${e.resource} with uuid ${e.uuid} not found`),t;if(e=o,typeof e=="object"&&(e.__useCount=e.__useCount?e.__useCount+1:1),t===e)return t;if(e&&typeof e=="object"){if((e.constructor||Object)!==Object)return t&&console.warn("Serialization: replacing object",t,"with deserialized object",e),e;console.error("Serialization: during Deserialize, meta should only have class instances, not js objects",e,t,i)}}if(e&&typeof e=="object"&&(e.constructor||Object)!==Object&&!Array.isArray(e)&&!e.serializableClassId){if(e instanceof Blob)return e;console.warn("Serialization: Data might already be deserialized. It will be cloned, or copied to source",e,"source",t,e.constructor,e.constructor!==Object)}if(e&&typeof e=="object"){const a=o=>{const l=xs.SerializableClasses.get(o);l&&(l.DataInConstructor?t=new l(e):t=new l)};e.serializableClassId&&(!t||t.serializableClassId!==e.serializableClassId)&&a(e.serializableClassId),e.type&&(!t||t.type!==e.type)&&a(e.type),!Array.isArray(t)&&Array.isArray(e)?t=[]:typeof t!="object"&&(e.constructor||Object)===Object&&(t={})}if(typeof t=="function")return console.error("Serialization: Cannot deserialize into a function",t,e),t;if(!n){const a=xs.GetSerializer(e);if(a&&a!==qy)return a.deserialize(e,t,i)}if(!e||t===void 0||t===null||typeof t!="object")return e;if(!n&&typeof t?.fromJSON=="function")return t.fromJSON(e,i,!0),t;let s=t.constructor??Object;if(s===Object)return qy.deserialize(e,t,i);for(;s&&s!==Object;){const a=xs.TypeMap.get(s)??[];for(const[o,l]of a){const c=t[l],h=xs.Deserialize(e[o],c,i,!1);h!==c&&an(t,l,h,!0)}s=Object.getPrototypeOf(s)}return t}};cl.TypeMap=new Map,cl.SerializableClasses=new Map,cl.Serializers=[{priority:0,isType:r=>Array.isArray(r),serialize:(r,e)=>r.map(t=>cl.Serialize(t,e,!1)),deserialize:(r,e,t)=>{const i=r.length;Array.isArray(e)||(e=[]);for(let n=0;n<i;n++){const s=r[n],a=e.length>n?cl.Deserialize(s,e[n],t,!1):cl.Deserialize(s,void 0,t,!1);e.length<=n?e.push(a):e[n]=a}return e}},{priority:0,isType:r=>!r||typeof r!="object",serialize:r=>{if(r&&typeof r=="number"){if(r===1/0)return"Infinity";if(r===-1/0)return"-Infinity";if(isNaN(r))return"NaN"}return r},deserialize:(r,e)=>{if(typeof e=="number"){if(r==="Infinity")return 1/0;if(r==="-Infinity")return-1/0;if(r==="NaN")return NaN;if(typeof r=="number"||!r)return r}return r}},qy];let Bt=cl;const tS=class $g{static callFunction(e,t,i=[]){if(!t)return e(...i);if(e.name&&t[e.name]===e)return e.call(t,...i);$g.methodMap.has(t)||$g.methodMap.set(t,new WeakMap);const n=$g.methodMap.get(t);if(!n.has(e)){let s=t;for(;s;){const a=Object.values(Object.getOwnPropertyDescriptors(s));for(let o of a)if(o.value===e)return n.set(e,!0),e.call(t,...i);s=Object.getPrototypeOf(s)}n.set(e,!1)}return n.get(e)?e.call(t,...i):e(...i)}};tS.methodMap=new WeakMap;let zu=tS;function de(r,e="param"){if(!r)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return(t,i,n)=>{const s={get(){return this[`_oc_${i}`]},set(a){var o;const l=this[`_oc_${i}`];if(l===a)return;this[`_oc_${i}`]=a;const c=e==="param"?[i,a,l,this]:e==="object"?[{key:i,value:a,oldValue:l,target:this}]:[];typeof r=="string"?(o=this[r])==null||o.call(this,...c):typeof r=="function"&&zu.callFunction(r,this,c)}};if(n)return qn(n,"value")&&delete n.value,qn(n,"writable")&&delete n.writable,qn(n,"initializer")&&delete n.initializer,Object.assign(n,s);Object.defineProperty(t,i,s)}}function ei(r,e="void"){if(!r)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return de(r,e)}function tt(r,e="object"){if(!r)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return de(r,e)}function so(r){return de((e,t,i,n)=>{if(!n.dispatchEvent)throw new Error("onChangeDispatchEvent: target does not have dispatchEvent");n.dispatchEvent({type:r||`${e}-changed`,detail:{key:e,value:t,oldValue:i}})},"param")}function z(r){return(e,t)=>{const i=e.constructor;if(i===Object)throw new Error("All properties in an object are serialized by default");Bt.TypeMap.has(i)||Bt.TypeMap.set(i,[]),Bt.TypeMap.get(i).push([r||t,t])}}function Vc(r){return e=>(e=class extends e{constructor(){super(...arguments),this.serializableClassId=r}},Bt.SerializableClasses.set(r,e),e)}async function iS(r,e,t,i=12){const n=typeof e=="string"?new TextEncoder().encode(e):e,s=await crypto.subtle.digest("SHA-256",n),a=crypto.getRandomValues(new Uint8Array(i)),o=Array.from(a).map(y=>String.fromCharCode(y)).join(""),l={name:"AES-GCM",iv:a},c=await crypto.subtle.importKey("raw",s,l,!1,["encrypt"]),h=typeof r=="string"?new TextEncoder().encode(r):r,u=await crypto.subtle.encrypt(l,c,h),d=new Uint8Array(u),p=Array.from(d),m=p.map(y=>String.fromCharCode(y)).join(""),A=t?typeof t=="string"?t:new TextDecoder().decode(t):"",g=t?typeof t=="string"?new TextEncoder().encode(t):Array.from(t):[];return typeof r=="string"?A+o+m:new Uint8Array([...g,...a,...p])}async function nS(r,e,t=12){const i=typeof e=="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",i),s=r.slice(0,t),a={name:"AES-GCM",iv:typeof s=="string"?new Uint8Array(Array.from(s).map(h=>h.charCodeAt(0))):s},o=await crypto.subtle.importKey("raw",n,a,!1,["decrypt"]),l=r.slice(t),c=typeof l=="string"?new Uint8Array(Array.from(l).map(h=>h.charCodeAt(0))):l;try{const h=await crypto.subtle.decrypt(a,o,c);return typeof r=="string"?new TextDecoder().decode(h):new Uint8Array(h)}catch{throw new Error("Decrypt failed")}}async function xU(){return"showOpenFilePicker"in window?window.showOpenFilePicker().then(r=>r[0]):window.chooseFileSystemEntries()}function SU(){if("showSaveFilePicker"in window){const e={types:[{description:"Text file",accept:{"text/plain":[".txt"]}}]};return window.showSaveFilePicker(e)}const r={type:"save-file",accepts:[{description:"Text file",extensions:["txt"],mimeTypes:["text/plain"]}]};return window.chooseFileSystemEntries(r)}function EU(r){return r.text?r.text():MU(r)}function MU(r){return new Promise(e=>{const t=new FileReader;t.addEventListener("loadend",i=>{const n=(i.srcElement||i.target).result;e(n)}),t.readAsText(r)})}async function TU(r,e){if(r.createWriter){const i=await r.createWriter();await i.write(0,e),await i.close();return}const t=await r.createWritable();await t.write(e),await t.close()}async function IU(r,e){const t={};return e&&(t.writable=!0,t.mode="readwrite"),await r.queryPermission(t)==="granted"||await r.requestPermission(t)==="granted"}function Xy(r,e=8192,t=!1){var i;const n=r.width||r.videoWidth,s=r.height||r.videoHeight;if(!n||!s)throw new Error("Invalid bitmap");const a=document.createElement("canvas");a.width=Math.min(e,n),a.height=Math.floor(1+a.width*s/n);const o=r instanceof ImageBitmap,l=o&&t&&Math.abs(a.width-n)<.5?a.getContext("bitmaprenderer"):void 0;return l?l.transferFromImageBitmap(r):(i=a.getContext("2d"))==null||i.drawImage(r,0,0,a.width,a.height),o&&t&&r.close(),a}function sS(r,e=8192,t=!1,i="image/png"){if(!(r.width||r.videoWidth)||!(r.height||r.videoHeight))return"";const n=Xy(r,e,!1),s=n.toDataURL(i);return n.remove(),t&&r instanceof ImageBitmap&&r.close(),s}async function PU(r,e=8192,t=!1,i="image/png"){if(!(r.width||r.videoWidth)||!(r.height||r.videoHeight))return Promise.reject("Invalid bitmap");const n=Xy(r,e,!1);return new Promise((s,a)=>{n.toBlob(o=>{o?s(o):a("Could not get blob"),n.remove(),t&&r instanceof ImageBitmap&&r.close()},i)})}async function rS(r){return new Promise((e,t)=>{const i=new Image;i.addEventListener("load",()=>{const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");if(!s){t(new Error("Could not get 2d context"));return}s.drawImage(i,0,0,n.width,n.height);const a=s.getImageData(0,0,n.width,n.height);e(a),n.remove(),i.remove()},!1),i.addEventListener("error",n=>{i.remove(),t(n)},!1),i.src=r})}function aS(r,{backgroundColor:e="",scale:t=1,width:i=512,height:n=512}){const s=document.createElement("canvas"),a=s.getContext("2d"),o=t,l=i,c=n;return s.width=l*o,s.height=c*o,s.style.width=`${l}`,s.style.height=`${c}`,e?.length>0&&(a.fillStyle=e,a.fillRect(0,0,s.width,s.height)),a.drawImage(r,0,0,s.width,s.height),s}function DU(r){const e=document.createElement("canvas");return e.width=r.width,e.height=r.height,e.getContext("2d").putImageData(r,0,0),e}function RU(){const r=document.createElement("canvas");return r.getContext&&r.getContext("2d")?r.toDataURL("image/webp").startsWith("data:image/webp"):!1}function Yy(r){const e=document.createElement("canvas");e.width=r.width||r.videoWidth||1,e.height=r.height||r.videoHeight||1;const t=e.getContext("2d");if(!t)throw new Error("Unable to get 2d context");return t.translate(0,r.height||r.videoHeight||1),t.scale(1,-1),t.drawImage(r,0,0),e}function BU(r){return new Promise((e,t)=>{const i=new Image,n=URL.createObjectURL(r);i.onload=()=>{URL.revokeObjectURL(n),e(i)},i.onerror=s=>{URL.revokeObjectURL(n),t(s)},i.src=n})}const LU=r=>`data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='16' height='16' fill='%23${r}'/%3E%3C/svg%3E%0A`,oS=r=>`data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='8' cy='8' r='7' fill='%23${r}'/%3E%3C/svg%3E%0A`,OU=r=>`data:image/svg+xml,%3Csvg viewBox='0 0 80 14' xmlns='http://www.w3.org/2000/svg'%3E%3Ctext style='font: 8px "Roboto Mono", "Source Code Pro", Menlo, Courier, monospace; fill: white;' x='9' y='9'%3E${r}%3C/text%3E%3C/svg%3E%0A`,$y=async(r,e)=>{const t=await kx(r);return aS(t,e)},lS=async(r,e)=>await $y(r,e).then(t=>t.toDataURL("image/png")),UU=async r=>qp(await(await fetch(r)).blob());async function cS(r,e=UU){const t=r.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g);if(t)for(const i of t){const n=await e(i);r=r.replace(i,n)}return r}function Ky(r,e,{width:t,height:i},n=!0){const s=`
<svg viewBox="0 0 ${t} ${i}" xmlns="http://www.w3.org/2000/svg">
    <style>
    ${e}
    </style>
    <foreignObject x="0" y="0" width="100%" height="100%">
        <div xmlns="http://www.w3.org/1999/xhtml" style="height: 100%; width: 100%; position: absolute: top:0; left:0">
            ${r}
        </div>
    </foreignObject>
</svg>
    `;return n?jy(s):s}async function FU(r,e,t){const i=Ky(r,e,t);return await $y(i,t)}async function NU(r,e,t){const i=Ky(r,e,t);return await lS(i,t)}function hS(r,e){return Math.abs(r)>Math.abs(e)?r:e}function Jy(r,e,t){const i=t?1:0,n=~(1<<e);return r&n|i<<e}function kU(r,e){const t=~(1<<e);return r&t}function Zy(){const r=(i,n)=>i.toString(16).padStart(n,"0"),e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=new DataView(e.buffer);return`${r(t.getUint32(0),8)}-${r(t.getUint16(4),4)}-${r(t.getUint16(6),4)}-${r(t.getUint16(8),4)}-${r(t.getUint32(10),8)}${r(t.getUint16(14),4)}`}function Vu(r,e=null){var t;return(t=window?.location)!=null&&t.href?new URL(window.location.href).searchParams.get(r)??e:e}function GU(r,e,t=!1){var i;if(!((i=window?.location)!=null&&i.href))return;const n=new URLSearchParams(window.location.search);e==null?n.has(r)&&n.delete(r):n.set(r,e),t?window.location.search=n.toString():window.history.replaceState({},"","?"+n.toString())}function zU(r,e="/"){return r.join(e)}function VU(r,e){const t=(e?`var Module = { locateFile: function(s) { return "${e}"; } }; 
`:"")+`importScripts( "${r}" );`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))}const uS={alert:async r=>window.alert(r),prompt:async(r,e,t)=>window.prompt(r,e),confirm:async r=>window.confirm(r),confirmSync:r=>window.confirm(r)},HU='.dialog-container{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:1000;border-radius:10px;padding:20px;max-width:calc(100% - 32px);width:calc(100% - 32px);color:#0a0a0a;background-color:#fff;border:1px solid oklch(.922 0 0);box-shadow:#0000 0 0,#0000 0 0,#0000 0 0,#0000 0 0,#0000001a 0 10px 15px -3px,#0000001a 0 4px 6px -4px;display:flex;gap:1rem;flex-direction:column;box-sizing:border-box;font-family:Inter,-apple-system,"system-ui",Segoe UI,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";transition:max-width .5s,width .5s,height .5s}.dialog-content{display:flex;flex-direction:column;gap:.5rem;text-align:center}.dialog-title{font-size:1.125rem;font-weight:600;line-height:1.5;color:#0a0a0a}.dialog-message{color:#737373;font-size:.875rem;line-height:1.42}.dialog-footer{display:flex;gap:10px;flex-direction:column-reverse}@media (width >= 40rem){.dialog-content{text-align:left}.dialog-container{max-width:512px;width:512px}.dialog-footer{flex-direction:row;justify-content:flex-end}}.dialog-button,.dialog-input{height:2.25rem;box-sizing:border-box}.dialog-input{width:100%;padding:.25rem .75rem;font-size:1rem;border:1px solid oklch(.922 0 0);border-radius:.5rem;background:transparent;color:#0a0a0a;outline:none;transition:outline-width .2s}.dialog-button{padding:.5rem 1rem;box-shadow:#0000 0 0,#0000 0 0,#0000 0 0,#0000000d 0 1px 2px;border-radius:.5rem;border:1px solid oklch(.922 0 0);cursor:pointer;font-size:.875rem;background-color:#fff;color:#0a0a0a;transition:background-color .2s ease,color .2s ease,outline-width .2s ease}.dialog-button:focus,.dialog-input:focus{outline:3px solid #6d7a8c66}.dialog-button:hover{background-color:#f8f8f8}.dialog-ok{background-color:#0a0a0a;color:#fff}.dialog-ok:hover{background-color:#222}.dialog-link{max-width:100%;display:inline-block;vertical-align:bottom;text-decoration:underline;color:var(#2563eb);overflow:hidden}.dialog-link-text{display:inline-block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:bottom}';let Xp=null;function QU(r){const e=/((https?:\/\/|www\.)[^\s<]+)/g;return r.replace(e,t=>{let i=t;return i.startsWith("http")||(i="https://"+i),`<a href="${i}" target="_blank" rel="noopener noreferrer" class="dialog-link"><span class="dialog-link-text">${Vs(t)}</span></a>`})}function jU(r){const e=Vs(r);return QU(e).replace(/\n/g,"<br>")}function ev(r){return`
${r.title?`<div class="dialog-title">${Vs(r.title)}</div>`:""}
<div class="dialog-message">${jU(r.message)}</div>
`}const WU=r=>`
<div class="dialog-content">
${ev(r)}
</div>
<div class="dialog-footer">
    ${r.ok&&`<button class="dialog-button dialog-ok">${Vs(r.ok)}</button>`||""}
</div>
`,qU=r=>`
<div class="dialog-content">
${ev(r)}
</div>
<div class="dialog-footer">
    ${r.cancel&&`<button class="dialog-button dialog-cancel">${Vs(r.cancel)}</button>`||""}
    ${r.ok&&`<button class="dialog-button dialog-ok">${Vs(r.ok)}</button>`||""}
</div>
`,XU=r=>`
<div class="dialog-content">
    ${ev(r)}
    <input class="dialog-input" type="text" value="${r.defaultValue??""}" style="margin-top:0.5rem;"/>
</div>
<div class="dialog-footer">
    ${r.cancel&&`<button class="dialog-button dialog-cancel">${Vs(r.cancel)}</button>`||""}
    ${r.ok&&`<button class="dialog-button dialog-ok">${Vs(r.ok)}</button>`||""}
</div>
`;function YU(){Xp||(Xp=document.createElement("style"),Xp.textContent=HU,document.head.appendChild(Xp))}function tv(r,{message:e,...t}){YU();const i=document.createElement("div"),n=e?.split(":")[0];return n&&e&&(e=e.replace(n+":","").trim()),i.innerHTML=r({...t,message:e,title:n}),i.classList.add("dialog-container"),document.body.appendChild(i),i}const $U={alert:async r=>{const e=tv(WU,{message:r||"Alert",ok:"Okay"});return new Promise(t=>{const i=e.querySelector(".dialog-ok"),n=a=>{(a.key==="Enter"||a.key==="Escape")&&(a.preventDefault(),i?.click())},s=()=>{window.removeEventListener("keydown",n),document.body.removeChild(e)};window.addEventListener("keydown",n),i?.addEventListener("click",()=>{s(),t()}),i?.focus()})},prompt:async(r,e,t=!0)=>{const i=tv(XU,{message:r||"Enter some text",ok:"OK",cancel:t?"Cancel":void 0,defaultValue:e});return new Promise(n=>{const s=i.querySelector(".dialog-ok"),a=i.querySelector(".dialog-cancel"),o=i.querySelector(".dialog-input");o.addEventListener("keydown",h=>{h.key==="Enter"&&(h.preventDefault(),s?.click())});const l=h=>{h.key==="Escape"&&a&&(h.preventDefault(),a?.click())},c=()=>{window.removeEventListener("keydown",l),document.body.removeChild(i)};window.addEventListener("keydown",l),s?.addEventListener("click",()=>{const h=o.value;c(),n(h)}),a?.addEventListener("click",()=>{c(),n(null)}),o?.focus(),o?.select()})},confirm:async r=>{const e=tv(qU,{message:r||"Are you sure?",ok:"Yes",cancel:"No"});return new Promise(t=>{const i=e.querySelector(".dialog-ok"),n=e.querySelector(".dialog-cancel"),s=o=>{o.key==="Escape"&&n&&(o.preventDefault(),n.click())},a=()=>{window.removeEventListener("keydown",s),document.body.removeChild(e)};window.addEventListener("keydown",s),i?.addEventListener("click",()=>{a(),t(!0)}),n?.addEventListener("click",()=>{a(),t(!1)}),n?.focus()})},confirmSync:r=>window.confirm(r)};function ga(r){return r===null||typeof r!="object"?r:Array.isArray(r)?r.map(ga):!r._ui_isPrimitive&&typeof r.clone=="function"&&r._ui_primitiveClone!==!1?r.clone():r}function Hu(r,e){return r===null||typeof r!="object"?r===e:Array.isArray(r)?Array.isArray(e)&&r.length===e.length&&r.every((t,i)=>Hu(t,e[i])):!r._ui_isPrimitive&&typeof r.equals=="function"&&r._ui_primitiveEquals!==!1?!!r.equals(e):r===e}function Qu(r,e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))if(r&&Array.isArray(r)){if(r.length<e.length){for(let t=0;t<r.length;t++)r[t]=Qu(r[t],e[t]);for(let t=r.length;t<e.length;t++)r.push(ga(e[t]))}else{for(let t=0;t<e.length;t++)r[t]=Qu(r[t],e[t]);r.length=e.length}return r}else return ga(e);else return!e._ui_isPrimitive&&typeof e.copy=="function"&&e._ui_primitiveCopy!==!1?r&&typeof r=="object"&&!Array.isArray(r)&&!r._ui_isPrimitive&&typeof r.copy=="function"&&r._ui_primitiveCopy!==!1?(r.copy(e),r):ga(e):e}function Yp(r,e,t,i=2e3){if(!r||!r.enabled)return;const n=e;if(n.type!==t)return r.record(e);const s=r.peek();let a=!!s&&s.type===t&&s.uid===n.uid;if(a){const o=s;!o.final&&n.time-o.time<i?(n.lastVal=o.lastVal,n.val=ga(n.val),r.replaceLast(n)):a=!1}a||Hu(n.lastVal,n.val)||(n.val=ga(n.val),r.record(n))}function iv(r,e,t,i,n,s,a=!0,o=2e3,l=!1,c){const[h,u]=e,d=i.lastValue??h?.[u];let p=!1;const m=i.last??!0,A=Hu(d,t),g=ga(d);A?p=!m:h?Qu(d,t)!==d?p=!an(h,u,t,!0,!0):p=!1:p=!0;const y=!p&&(m||!A);return a&&y&&r&&Yp(r,{type:s,lastVal:g,val:t,final:m,props:i,time:Date.now(),uid:n,binding:l?e:void 0,onUndoRedo:c},s,o),{last:m,value:t,lastValue:g,undoable:y}}function nv(r,e){let t=r,i;for(;!i&&t;)t=Object.getPrototypeOf(t),t&&(i=Object.getOwnPropertyDescriptor(t,e));return{proto:t,protoDesc:i}}function Hc(r){return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("data:")||r.startsWith("asset://")||r.startsWith("/")||r.startsWith("//")}const sv={simpleCameraHelpers:`#ifndef SIMPLE_CAMERA_HELPERS
#define SIMPLE_CAMERA_HELPERS
#ifndef USE_TRANSMISSION
uniform mat4 projectionMatrix;
#endif
vec3 viewToScreen(const in vec3 pos){vec4 projected=projectionMatrix*vec4(pos,1.0);return vec3(0.5+0.5*projected.xy/projected.w,projected.w);}vec3 screenToView(const in vec2 uv,const in float viewZ){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projectionMatrix[2][0])*viewZ/projectionMatrix[0][0];float ye=-(uv_.y+projectionMatrix[2][1])*viewZ/projectionMatrix[1][1];return vec3(xe,ye,viewZ);}
#endif
`,cameraHelpers:`#ifndef BASIC_CAMERA_HELPERS
#define BASIC_CAMERA_HELPERS
uniform mat4 projection;uniform vec2 cameraNearFar;uniform vec3 cameraPositionWorld;
#ifndef THREE_PACKING_INCLUDED
#define THREE_PACKING_INCLUDED
#include <packing>
#endif
float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}float depthToViewZ(const in float depth){return(depth>0.999)?-cameraNearFar.y*1000.0 :-mix(cameraNearFar.x,cameraNearFar.y,depth);}float viewZToDepth(const in float viewZ){return linstep(-cameraNearFar.x,-cameraNearFar.y,viewZ);}vec4 viewToScreen3(const in vec3 pos){vec4 projected=projection*vec4(pos,1.0);projected.z=pos.z;projected.w=1./projected.w;projected.xyz*=projected.w;projected.xy=0.5+0.5*projected.xy;return projected;}vec3 screenToView3(const in vec2 uv,const in float viewZ){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projection[2][0])*viewZ/projection[0][0];float ye=-(uv_.y+projection[2][1])*viewZ/projection[1][1];return vec3(xe,ye,viewZ);}float viewZFromNDCZ(const in float depth){
#if PERSPECTIVE_CAMERA == 1
return perspectiveDepthToViewZ(depth,cameraNearFar.x,cameraNearFar.y);
#else
return orthographicDepthToViewZ(depth,cameraNearFar.x,cameraNearFar.y);
#endif
}
#endif
`,randomHelpers:`#ifndef BASIC_RANDOM_HELPERS
#define BASIC_RANDOM_HELPERS
float random(float n){return fract(sin(n)*43758.5453123);}float random2(vec2 n,float x){n+=x;return fract(sin(dot(n.xy,vec2(12.9898,78.233)))*43758.5453);}float random3(vec3 v){v=fract(v*443.8975);v+=dot(v,v.yzx+19.19);return fract((v.x+v.y)*v.z);}float interleavedGradientNoise(const in vec2 fragCoord,const in float seed){vec3 magic=vec3(0.06711056,0.00583715,52.9829189);return fract(magic.z*fract(dot(fragCoord.xy+seed*vec2(2.083,4.867),magic.xy)));}vec3 hash3(vec2 p){vec3 q=vec3(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)),dot(p,vec2(419.2,371.9)));return fract(sin(q)*43758.5453);}
#endif
`,defaultVertex:"varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}",defaultFragment:"varying vec2 vUv;void main(){gl_FragColor=vec4(vUv,0.0,1.0);}",voronoiNoise:`#ifndef VORONOI_HELPER
#define VORONOI_HELPER
float voronoi_distance(vec2 a,vec2 b,float metric){return distance(a,b);}float voronoi_f1_2d(in vec2 coord,in float randomness,in float flakeClamp,in float flakeRadius,inout vec3 outColor){vec2 cellPosition=floor(coord);vec2 localPosition=coord-cellPosition;float minDistance=8.0;vec2 targetOffset,targetPosition;for(int j=-1;j<=1;j++){for(int i=-1;i<=1;i++){vec2 cellOffset=vec2(i,j);vec2 pointPosition=cellOffset+hash3(cellPosition+cellOffset).xy*randomness;float distanceToPoint=voronoi_distance(pointPosition,localPosition,1.);if(distanceToPoint<minDistance){targetOffset=cellOffset;minDistance=distanceToPoint;targetPosition=pointPosition;}}}float outDistance=minDistance;float dist=step(flakeRadius,outDistance);outColor=hash3(cellPosition+hash3(cellPosition+targetOffset).xy*randomness+targetOffset);vec3 outColor1=minDistance<flakeRadius ? outColor : vec3(0.5,0.5,1.);outDistance=mix(dist,minDistance,flakeClamp);outColor=mix(outColor1,outColor,flakeClamp);return outDistance;}
#endif
`};/**
 * @license
 * uiconfig.js v0.3.1
 * Copyright 2022-2025 repalash <palash@shaders.app>
 * MIT License
 * See ./dependencies.txt for bundled third-party dependencies and licenses.
 */const dS=class{};dS.Map=new Map;let ju=dS;function ti(r,e,t,i,n=!0){i=i??r[e],t=t??e+"";const s=i?.uiConfig;let a;if(s)a=s;else{const o=KU(i);o==="folder"?a=$p(t,i,{},"folder",n):o&&(a={type:o,label:t,property:[r,e]})}return a&&!a.label&&(a.label=t),a}function vi(r){if(!r)return[];let e=r.constructor||Object;e===Array&&(e=Object);const t=[],i=[];for(;e&&e!==Object;)i.push(e),e=Object.getPrototypeOf(e);if(!i.length||Array.isArray(r)){const n=typeof r=="object"?Object.keys(r):Array.isArray(r)?r.map((s,a)=>a):[];for(const s of n){const a=r[s];if(a==null)continue;const o=ti(r,s,s+"",a,!0);o&&t.push(o)}}return i.reverse().forEach(n=>{var s;(s=ju.Map.get(n))==null||s.forEach(({params:a,propKey:o,uiType:l})=>{let c;if(l||(c=()=>ti(r,o)),c||(c={property:[r,o],type:l||"input"}),a){const h=typeof a.params=="function"?a.params(r):a.params||{},u={...a};if(delete u.params,typeof c=="function"){const d=c;c=()=>{const p=d();return p&&Object.assign(p,{...u,...h})}}else Object.assign(c,{...u,...h})}t.push(c)})}),t}function $p(r,e,t={},i="folder",n=!1){return{type:i,label:r,children:n?[()=>vi(e)]:vi(e),uuid:Zy(),...t}}function KU(r){return r==null?null:Array.isArray(r)?"folder":typeof r=="boolean"?"checkbox":typeof r=="number"?"number":typeof r=="string"?"input":typeof r=="function"?"button":typeof r.x=="number"?"vec":typeof r.r=="number"?"color":r.isTexture?"image":typeof r=="object"?"folder":null}function JU(r){return(e,t)=>{const i=e.constructor;if(i===Object)throw new Error("Not possible to use uiConfig decorator on an object, use class instead");ju.Map.has(i)||ju.Map.set(i,[]),r(e,t,ju.Map.get(i))}}function Li(r,e){return JU((t,i,n)=>{const s=n.findIndex(a=>a.propKey===i);if(s&&s<0)n.push({params:e||{},propKey:i,uiType:r});else throw new Error(`Property ${i} already has a uiConfig decorator`)})}function rv(r,e,t="panel"){return i=>class extends i{constructor(){super(...arguments),this.uiConfig=$p(it(r,this)||"",this,e||{},t)}}}function hl(r,e){return Li("monitor",{label:r,params:e})}function Oe(r,e,t,i){return Li("slider",{label:r,bounds:e,stepSize:t,params:i})}function gi(r,e,t,i){return Li("vec",{label:r,bounds:e,stepSize:t,params:i})}function Oi(r,e,t){return Array.isArray(e)&&typeof e[0]=="string"&&(e=e.map(i=>({label:i,value:i}))),Li("dropdown",{label:r,children:e,params:t})}function lt(r,e){return Li("button",{label:r,params:e})}function Fe(r,e){return Li("input",{label:r,params:e})}function Lt(r,e){return Li("number",{label:r,params:e})}function Tn(r,e){return Li("color",{label:r,params:e})}function Dr(r,e){return Li("image",{label:r,params:e})}function ae(r,e){return Li("checkbox",{label:r,params:e})}function Aa(r,e){return rv(r,e,"panel")}function gt(r,e){return rv(r,e,"folder")}const Kp={setValue:"UiConfigMethods_set",action:"UiConfigMethods_action"};class fS{constructor(e){this._renderer=e,this.undoEditingWaitTime=2e3,this.undoPresets={[Kp.setValue]:t=>{const i=()=>{var n,s;t.onUndoRedo&&t.onUndoRedo(t),(s=(n=t.uid).uiRefresh)==null||s.call(n,!1)};return{undo:()=>{this.setValue(t.uid,t.lastVal,t.props,void 0,!1).then(i)},redo:()=>{this.setValue(t.uid,t.val,t.props,void 0,!1).then(i)}}},[Kp.action]:t=>{const i=()=>{var n,s;t.onUndoRedo&&t.onUndoRedo(t),(s=(n=t.uid).uiRefresh)==null||s.call(n,!1)};return{undo:async()=>{await t.undo.call(t.target,...t.args),i()},redo:async()=>{await t.redo.call(t.target,...t.args),i()}}}}}getBinding(e,t=!0){let i=it(e.property,e);const n=it(e.path,e);if(i===void 0&&Object.hasOwn(e,"value")&&(i=[e,"value"]),i===void 0&&t&&(i=it(e.parentProperty,e)),!i||typeof i[0]!="object"||!i[1])return[void 0,""];if(typeof i[1]=="string"&&n&&n.length&&(i=[i[0],i[1]+"."+n]),typeof i[1]=="string"&&i[1].includes(".")){const s=i[1].split(".");let a=i[0];const o=s.pop()||"";for(const l of s)if(a=Array.isArray(a)?a[parseInt(l)]:a[l],!a)return console.warn("Cannot determine property, invalid property path",e,i),[void 0,""];i=[a,o]}return Array.isArray(i[0])&&typeof i[1]=="string"&&(i[1]=parseInt(i[1])),i}getRawValue(e){const[t,i]=this.getBinding(e);return t?t[i]:void 0}getValue(e,t,i=!0){const[n,s]=this.getBinding(e);if(!n)return;const a=n[s];return t!==void 0&&a!==void 0?Hu(t,a)&&!i?void 0:Qu(t,a):ga(a)}dispatchOnChangeSync(e,t,...i){var n;const s=[{type:"change",last:t.last??!0,config:t.config??e,configPath:[e,...t.configPath||[]],target:e,value:t.value,lastValue:t.lastValue},...i];typeof e.onChange=="function"?e.onChange(...s):Array.isArray(e.onChange)?e.onChange.flat().forEach(a=>typeof a=="function"&&a?.(...s)):e.onChange&&console.error("Invalid onChange type, must be a function or array of functions",e.onChange),(n=e.parentOnChange)==null||n.call(e,...s)}recordUndo(e){const t=this._renderer.undoManager;Yp(t,e,Kp.setValue,this.undoEditingWaitTime)}async performAction(e,t,i,n,s){var a,o,l;const c=()=>e===void 0?t(...i):t.call(e,...i);let h=await c();const u=typeof h=="function"?h:(a=h?.undo)==null?void 0:a.bind(h),d=typeof h!="function"?(o=h?.action)==null?void 0:o.bind(h):null,p=typeof h=="function"?c:((l=h?.redo)==null?void 0:l.bind(h))??d;typeof d=="function"&&(h=await d()),typeof u=="function"&&this.recordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:u,redo:p,args:i,onUndoRedo:s})}async setValue(e,t,i,n,s=!0){return this.runAtEvent(e,()=>{const a=this.getBinding(e),o=this._renderer.undoManager,l=iv(o,a,t,i,e,Kp.setValue,s,this.undoEditingWaitTime,!1,void 0);return!l.undoable&&!n?!1:(this.dispatchOnChangeSync(e,{...i,...l}),!0)})}async dispatchOnChange(e,t){return this.runAtEvent(e,()=>{this.dispatchOnChangeSync(e,t)})}getLabel(e){var t;return(it(e.label,e)??((t=this.getBinding(e))==null?void 0:t[1]))+""}getChildren(e){return(it(e.children,e)??[]).map(t=>it(t)).flat(2).filter(t=>t)}async clickButton(e,t){return this.runAtEvent(e,async()=>{const i=this.getBinding(e,!1),n=i[0],s=i[1],a=it(e.sendArgs,e)===!1?[]:t?.args??[],o=[];if(n){const l=n[s]??n.value;typeof l=="function"?o.push([l,n]):l&&console.warn("Invalid action type for button",l)}typeof e.onClick=="function"&&o.push([e.onClick,e]);for(const[l,c]of o)await this.performAction(c,l,a,e);await this.dispatchOnChange(e,{})})}async runAtEvent(e,t){const i=it(e.dispatchMode,e)??"postFrame";return i==="immediate"?t():new Promise(n=>{const s=async()=>{this._renderer.removeEventListener(i,s),n(await t())};this._renderer.addEventListener(i,s)})}initUiConfig(e){e&&(e.type||(console.warn("No type for config",e),e.type="input"),e.uuid||(e.uuid=Zy()),e.property===void 0&&(e.binding?e.property=e.binding:e.value===void 0?(e.getValue||e.setValue)&&(Object.defineProperty(e,"value",{get:()=>e.getValue&&e.getValue(),set:t=>e.setValue&&e.setValue(t)}),e.property=[e,"value"]):(e.getValue||e.setValue)&&console.warn("getValue/setValue is ignored since value is provided",e),e.property))}getBounds(e,t=!1){const i=it(e.bounds),n=(i?.length??0)>=2?i[1]:t?1/0:1,s=(i?.length??0)>=1?i[0]:t?-1/0:0,a=it(e.stepSize)||(t?.01:Math.pow(10,Math.floor(Math.log10((n-s)/100))));return{min:s,max:n,step:a}}}class pS extends Qp{constructor(e=!0,t,i){super(),this._rafId=null,this.raf=()=>{this._autoFrameEvents&&(this.dispatchEvent({type:"preFrame"}),this.dispatchEvent({type:"preRender"}),this.dispatchEvent({type:"postRender"}),this.dispatchEvent({type:"postFrame"}),this._rafId=requestAnimationFrame(this.raf))},this._refreshQueue={preRender:[],postRender:[],preFrame:[],postFrame:[]},this._lastModeTime={preRender:0,postRender:0,preFrame:0,postFrame:0},this.methods=t||new fS(this),this.undoManager=i===!1?void 0:i||new Hy({bindHotKeys:!0,limit:1e3,debug:Vu("debugUndo")!==null}),this._autoFrameEvents=e,e&&(this.addEventListener("preFrame",()=>this.refreshQueue("preFrame")),this.addEventListener("postFrame",()=>this.refreshQueue("postFrame")),this.addEventListener("preRender",()=>this.refreshQueue("preRender")),this.addEventListener("postRender",()=>this.refreshQueue("postRender")))}get undoManager(){return this._undoManager}set undoManager(e){this._undoManager=e,this._undoManager&&Object.assign(this._undoManager.presets,this.methods.undoPresets)}start(){this._rafId===null&&(this._rafId=requestAnimationFrame(this.raf))}stop(){this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}refreshQueue(e){const t=this._refreshQueue[e],i=[],n=Mn(),s=n-this._lastModeTime[e];t.forEach(a=>{a[1]>.001?(a[1]-=s,i.push(a)):this._refreshUiConfigObject(a[0])}),this._refreshQueue[e]=i,this._lastModeTime[e]=n}_addToRefreshQueue(e,t,i){const n=t.uuid,s=this._refreshQueue[e],a=s.find(o=>o[2]===n);a?a[1]=Math.max(a[1],i):s.push([t,i,n]),this._refreshQueue[e]=s}disposeUiConfig(e,t=!0){var i,n;e&&(e.uiRef&&(t&&((n=(i=e.uiRef).dispose)==null||n.call(i)),e.uiRef=void 0),e.uiRefType=void 0,e.uiRefresh=void 0)}addToRefreshQueue(e,t,i,n){const s=i?this._flattenUiConfig(t):[t];for(const a of s)e==="immediate"?jn(n).then(()=>this._refreshUiConfigObject(a)):this._addToRefreshQueue(e,a,n)}_flattenUiConfig(e,t){var i;return t=t??[],!e||!e.uiRef||(t.push(e),typeof e.children=="function")||(i=e.children)==null||i.forEach(n=>{typeof n!="function"&&n&&(Array.isArray(n)?n.forEach(s=>t=this._flattenUiConfig(s,t)):t=this._flattenUiConfig(n,t))}),t}}class ZU extends pS{constructor(e=document.body,t=!0,i,n){super(t,i,n),this.config={type:"panel",label:"Configuration",children:[]},this._uiContainer=this._createUiContainer(),e.appendChild(this._uiContainer),this.start()}unmount(){this.disposeUiConfig(this.config),this._uiContainer.remove(),this.stop()}appendChild(e,t){e&&(Object.assign(e,t),this.config.children.push(e),this.refreshRoot())}removeChild(e){const t=this.config.children.indexOf(e);t!==-1&&(this.config.children.splice(t,1),this.disposeUiConfig(e),this.refreshRoot())}refreshRoot(e=!0,t="postFrame",i=0){var n,s;(s=(n=this.config).uiRefresh)==null||s.call(n,e,t,i)}_createUiContainer(){return Pr({id:"uiConfigContainer",addToBody:!1})}}var eF=Object.defineProperty,tF=Object.getOwnPropertyDescriptor,Rr=(r,e,t,i)=>{for(var n=i>1?void 0:i?tF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&eF(e,t,n),n};f.ViewerTimeline=class extends wi{constructor(){super(...arguments),this._time=0,this.delta=0,this.endTime=2,this.resetOnEnd=!0,this.stopOnEnd=!1,this.running=!1,this._clock=new Lu(!1),this._start=!1,this._stop=!1,this._reset=!1,this._step=!1}get time(){return this._time}set time(e){this._time!==e&&this.setTime(e,!0)}shouldRun(){return this.running||this._step}start(){this._start=!0,this._stop&&(this._stop=!1),this._step&&(this._step=!1)}stop(){this._stop=!0,this._start&&(this._start=!1),this._step&&(this._step=!1)}reset(){this._reset=!0,this._step&&(this._step=!1)}update(e){if(this._refreshParams(),!this.running){this.delta=this._clock.getDelta(),this._time=this._clock.elapsedTime;return}const t=e.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();t&&t>0?(this.delta=t/1e3,this._clock.oldTime+=t,this._clock.elapsedTime+=this.delta,this._time=this._clock.elapsedTime,this.dispatchEvent({type:"update"})):t!==void 0&&t===0?(this.delta=0,this._time=this._clock.elapsedTime):(t===void 0||t<0)&&(this.delta=this._clock.getDelta(),this._time=this._clock.elapsedTime,this.dispatchEvent({type:"update"})),this._refreshParams()}_refreshParams(){const e=this.endTime>0&&this.time>=this.endTime&&this.running,t=this.resetOnEnd&&e,i=this.stopOnEnd&&e;(this._stop||i)&&(this._clock.stop(),this._start=!1,this._stop=!1,this.running=this._clock.running,this.dispatchEvent({type:"stop"})),this._start&&(this._clock.start(),this._clock.elapsedTime=this.time,this._start=!1,this.running=this._clock.running,this.dispatchEvent({type:"start"})),(this._reset||t)&&(this._clock.elapsedTime=0,this.time=0,this.delta=0,this._reset=!1,this.dispatchEvent({type:"reset"})),this.running=this._clock.running}update2(e){this._step=!1}setTime(e,t=!0){e<0&&(e=0),this._clock.elapsedTime=e,this._time=e,this.delta=0,this._reset=!1,this._start||(this._step=t),this.dispatchEvent({type:"update"})}},Rr([Fe("Time",{readOnly:!0})],f.ViewerTimeline.prototype,"time",1),Rr([Fe("Delta",{readOnly:!0})],f.ViewerTimeline.prototype,"delta",2),Rr([Fe("Max Time"),z(),so("endTimeChanged")],f.ViewerTimeline.prototype,"endTime",2),Rr([ae("Reset on End"),z(),so("resetOnEndChanged")],f.ViewerTimeline.prototype,"resetOnEnd",2),Rr([ae("Stop on End"),z(),so("stopOnEndChanged")],f.ViewerTimeline.prototype,"stopOnEnd",2),Rr([Fe("Running",{readOnly:!0})],f.ViewerTimeline.prototype,"running",2),Rr([lt("Start")],f.ViewerTimeline.prototype,"start",1),Rr([lt("Stop")],f.ViewerTimeline.prototype,"stop",1),Rr([lt("Reset")],f.ViewerTimeline.prototype,"reset",1),f.ViewerTimeline=Rr([Vc("ViewerTimeline"),gt("Timeline")],f.ViewerTimeline);function iF(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Jp={exports:{}},nF=Jp.exports,mS;function sF(){return mS||(mS=1,(function(r,e){(function(t,i){r.exports=i()})(nF,function(){var t=function(){function i(p){return a.appendChild(p.dom),p}function n(p){for(var m=0;m<a.children.length;m++)a.children[m].style.display=m===p?"block":"none";s=p}var s=0,a=document.createElement("div");a.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",a.addEventListener("click",function(p){p.preventDefault(),n(++s%a.children.length)},!1);var o=(performance||Date).now(),l=o,c=0,h=i(new t.Panel("FPS","#0ff","#002")),u=i(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=i(new t.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:a,addPanel:i,showPanel:n,begin:function(){o=(performance||Date).now()},end:function(){c++;var p=(performance||Date).now();if(u.update(p-o,200),p>l+1e3&&(h.update(1e3*c/(p-l),100),l=p,c=0,d)){var m=performance.memory;d.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return p},update:function(){o=this.end()},domElement:a,setMode:n}};return t.Panel=function(i,n,s){var a=1/0,o=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,u=48*c,d=3*c,p=2*c,m=3*c,A=15*c,g=74*c,y=30*c,_=document.createElement("canvas");_.width=h,_.height=u,_.style.cssText="width:80px;height:48px";var v=_.getContext("2d");return v.font="bold "+9*c+"px Helvetica,Arial,sans-serif",v.textBaseline="top",v.fillStyle=s,v.fillRect(0,0,h,u),v.fillStyle=n,v.fillText(i,d,p),v.fillRect(m,A,g,y),v.fillStyle=s,v.globalAlpha=.9,v.fillRect(m,A,g,y),{dom:_,update:function(b,T){a=Math.min(a,b),o=Math.max(o,b),v.fillStyle=s,v.globalAlpha=1,v.fillRect(0,0,h,A),v.fillStyle=n,v.fillText(l(b)+" "+i+" ("+l(a)+"-"+l(o)+")",d,p),v.drawImage(_,m+c,A,g-c,y,m,A,g-c,y),v.fillRect(m+g-c,A,c,y),v.fillStyle=s,v.globalAlpha=.9,v.fillRect(m+g-c,A,c,l((1-b/T)*y))}}},t})})(Jp)),Jp.exports}var rF=sF();const aF=iF(rF);class gS{constructor(e){this._stats=new aF,this._container=e,this._stats.dom.id="stats-js",this._stats.dom.style.position="absolute",this._stats.dom.style.left="unset",this._stats.dom.style.right="0"}show(){this._container.appendChild(this._stats.dom),this._stats.showPanel(0)}hide(){this._container.removeChild(this._stats.dom)}begin(){this._stats.begin()}end(){this._stats.end()}}const oF=".CustomContextMenu{position:absolute;background:#333e;min-width:8rem;color:#fff;font-size:.8rem;overflow:hidden;border-radius:8px;box-shadow:2px 2px 10px #6666;z-index:100000}.CustomContextMenu div{cursor:pointer;padding:6px 10px;transition:background-color .25s ease-in-out}.CustomContextMenu div:hover{background:#1a1a1c}#customContextMenu{background:#333e;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:.5px solid rgba(20,20,20,.3);width:auto;height:auto;position:absolute;display:flex;flex-direction:column;z-index:9999;padding:.4rem .25rem;border-radius:.375rem;min-width:8rem;pointer-events:auto;box-shadow:0 2px 10px #0c0c0c33}.customContextMenuItems{color:#fff;font-size:.8rem;font-family:monospace;background-color:transparent;cursor:pointer;padding:4px 8px;border-radius:.25rem;line-height:1rem;font-weight:500;transition:background-color .25s ease-in-out}.customContextMenuItems:hover{color:#fff;background-color:#017aff}",Vg=class Vg{static _initialize(){this._inited=!0,document.addEventListener("pointerdown",e=>{this.Element&&!this.Element.contains(e.target)&&e.button===0&&this.Remove()})}static Create(e,t,i,n=!0,s=!0){this._inited||this._initialize(),this.Element&&this.Remove();const a=document.createElement("div");a.id="customContextMenu",a.style.top=i+"px",a.style.left=t+"px",a.innerHTML="<style>"+oF+"</style>";for(const[o,l]of Object.entries(e)){const c=document.createElement("div");c.classList.add("customContextMenuItems"),c.textContent=o,a.appendChild(c),c.onclick=async()=>{await l(),s&&this.Remove()}}return this.Element=a,n&&document.body.appendChild(a),a}static Remove(){this.Element?.remove(),this.Element=void 0}};Vg.Element=void 0,Vg._inited=!1;let Wu=Vg;const Hg=class Hg{get inputEl(){return this._inputEl}get el(){return this._el}constructor(e,t,i){this._el=e,this._inputEl=t,this._listeners={drop:[],dropstart:[],droperror:[]},this._onDragover=this._onDragover.bind(this),this._onDrop=this._onDrop.bind(this),this._onSelect=this._onSelect.bind(this),e?.addEventListener("dragover",this._onDragover,!1),e?.addEventListener("drop",this._onDrop,!1),t?.addEventListener("change",this._onSelect),i&&Object.entries(i).forEach(([n,s])=>s&&this.on(n,s))}on(e,t){return this._listeners[e].push(t),this}_emit(e,t){return this._listeners[e].forEach(i=>i(t)),this}destroy(){const e=this._el,t=this._inputEl;e?.removeEventListener("dragover",this._onDragover),e?.removeEventListener("drop",this._onDrop),t?.removeEventListener("change",this._onSelect)}_onDrop(e){e.stopPropagation(),e.preventDefault(),this._emit("dropstart");const t=Array.from(e.dataTransfer?.files||[]),i=Array.from(e.dataTransfer?.items||[]);if(t.length===0&&i.length===0){this._fail("Required drag-and-drop APIs are not supported in this browser.");return}if(Hg.USE_DATA_TRANSFER_ITEMS&&i.length>0){const n=i.map(s=>s.webkitGetAsEntry());this._loadNextEntry(new Map,n,e);return}this._emit("drop",{nativeEvent:e,files:new Map(t.map(n=>(n.filePath=n.name,[n.filePath,n])))})}_onDragover(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}_onSelect(e){if(!this._inputEl){console.warn("Invalid Dropzone event ",e);return}this._emit("dropstart");const t=[].slice.call(this._inputEl.files??new FileList),i=new Map;t.forEach(n=>{n.filePath=n.webkitRelativePath||n.name,i.set(n.filePath,n)}),this._emit("drop",{files:i,nativeEvent:e})}_loadNextEntry(e,t,i){const n=t.pop();if(!n){this._emit("drop",{files:e,nativeEvent:i});return}if(n.isFile)n.file(s=>{s.filePath=n.fullPath,e.set(n.fullPath,s),this._loadNextEntry(e,t,i)},s=>console.error("Could not load file: %s",n.fullPath,s,"Try setting Dropzone.USE_DATA_TRANSFER_ITEMS to false."));else if(n.isDirectory){const s=n.createReader(),a=o=>{o.length?(t=t.concat(o),s.readEntries(a)):this._loadNextEntry(e,t,i)};s.readEntries(a)}else console.warn("Unknown asset type: "+n.fullPath),this._loadNextEntry(e,t,i)}_fail(e){this._emit("droperror",{message:e})}};Hg.USE_DATA_TRANSFER_ITEMS=!0;let Zp=Hg;const AS={type:"change"},av={type:"start"},yS={type:"end"},em=new Ha,vS=new Ts,lF=Math.cos(70*Ut.DEG2RAD);class ov extends wi{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new x,this.cursor=new x,this.minDistance=1e-5,this.maxDistance=1/0,this.autoPushTarget=!0,this.autoPullTarget=!0,this.clampMax=new x(1/0,1/0,1/0),this.clampMin=new x(-1/0,-1/0,-1/0),this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.maxZoomSpeed=1,this.maxZoomSpeed=1,this.dollyZoom=!1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.throttleUpdate=0,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:zl.ROTATE,MIDDLE:zl.DOLLY,RIGHT:zl.PAN},this.touches={ONE:Vl.ROTATE,TWO:Vl.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return o.phi},this.getAzimuthalAngle=function(){return o.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(I){I.addEventListener("keydown",Ne),this._domElementKeyEvents=I},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",Ne),this._domElementKeyEvents=null},this.saveState=function(){i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=function(){i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(AS),i.update(),s=n.NONE},this.update=(function(){const I=new x,ie=new Qe().setFromUnitVectors(e.up,new x(0,1,0)),X=ie.clone().invert(),Pe=new x,Ve=new Qe,jt=new x,Ot=2*Math.PI,Si=0;return function(ii=null){if(this.throttleUpdate&&this.throttleUpdate>=1&&Date.now()-Si<1e3/this.throttleUpdate)return;const es=i.object.position;I.copy(es).sub(i.target),I.applyQuaternion(ie),o.setFromVector3(I),i.autoRotate&&s===n.NONE&&O(C(ii)),i.enableDamping?(o.theta+=l.theta*i.dampingFactor,o.phi+=l.phi*i.dampingFactor):(o.theta+=l.theta,o.phi+=l.phi);let Ji=i.minAzimuthAngle,wn=i.maxAzimuthAngle;isFinite(Ji)&&isFinite(wn)&&(Ji<-Math.PI?Ji+=Ot:Ji>Math.PI&&(Ji-=Ot),wn<-Math.PI?wn+=Ot:wn>Math.PI&&(wn-=Ot),Ji<=wn?o.theta=Math.max(Ji,Math.min(wn,o.theta)):o.theta=o.theta>(Ji+wn)/2?Math.max(Ji,o.theta):Math.min(wn,o.theta)),o.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,o.phi)),o.makeSafe(),i.enableDamping===!0?i.target.addScaledVector(h,i.dampingFactor):i.target.add(h),i.target.sub(i.cursor),i.target.clampLength(i.minTargetRadius,i.maxTargetRadius),i.target.add(i.cursor);let To=0,Xr=!1;if(i.zoomToCursor&&E||i.object.isOrthographicCamera)o.radius=re(o.radius);else{const Cn=o.radius;Math.abs(l.radius)>0&&(i.dollyZoom&&(i.object.zoom=Math.max(Math.max(i.minZoom,.1),Math.min(Math.min(i.maxZoom,20),i.object.zoom*(1+l.radius*(i.enableDamping?i.dampingFactor:1)))),i.object.updateProjectionMatrix(),(i.object.zoom>=Math.min(i.maxZoom,20)||i.object.zoom<=Math.max(i.minZoom,.1))&&(l.radius=0)),o.radius*=1+l.radius*(i.enableDamping?i.dampingFactor:1)),Math.abs(c-1)>1e-5&&(i.dollyZoom&&(i.object.zoom=Math.max(Math.max(i.minZoom,.1),Math.min(Math.min(i.maxZoom,20),i.object.zoom*c)),i.object.updateProjectionMatrix(),(i.object.zoom>=Math.min(i.maxZoom,20)||i.object.zoom<=Math.max(i.minZoom,.1))&&(c=1)),o.radius*=c),i.autoPushTarget&&o.radius<i.minDistance&&(To=i.minDistance-o.radius),i.autoPullTarget&&o.radius>i.maxDistance&&(To=i.maxDistance-o.radius),o.radius=re(o.radius),Xr=Cn!=o.radius}I.setFromSpherical(o),I.applyQuaternion(X),es.copy(i.target).add(I),i.target.add(I.normalize().multiplyScalar(-To)),es.clamp(i.clampMin,i.clampMax),i.target.clamp(i.clampMin,i.clampMax),i.object.lookAt(i.target);let Ua=!1;if(i.enableDamping===!0&&Math.abs(l.theta)+Math.abs(l.phi)+Math.abs(l.radius)+h.length()>.001?(l.theta*=1-i.dampingFactor,l.phi*=1-i.dampingFactor,l.radius*=1-i.dampingFactor,h.multiplyScalar(1-i.dampingFactor),Ua=!0):(l.set(0,0,0),h.set(0,0,0)),i.zoomToCursor&&E){let Cn=null;if(i.object.isPerspectiveCamera){const Cs=o.radius;Cn=o.radius*c,Cn=re(Cn);const ts=Cs-Cn;i.object.position.addScaledVector(b,ts),i.object.updateMatrixWorld(),Xr=!!ts}else if(i.object.isOrthographicCamera){const Cs=new x(T.x,T.y,0);Cs.unproject(i.object);const ts=i.object.zoom;i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/c)),i.object.updateProjectionMatrix(),Xr=ts!==i.object.zoom;const Pt=new x(T.x,T.y,0);Pt.unproject(i.object),i.object.position.sub(Pt).add(Cs),i.object.updateMatrixWorld(),Cn=o.radius}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),i.zoomToCursor=!1;Cn!==null&&(this.screenSpacePanning?i.target.set(0,0,-1).transformDirection(i.object.matrix).multiplyScalar(Cn).add(i.object.position):(em.origin.copy(i.object.position),em.direction.set(0,0,-1).transformDirection(i.object.matrix),Math.abs(i.object.up.dot(em.direction))<lF?e.lookAt(i.target):(vS.setFromNormalAndCoplanarPoint(i.object.up,i.target),em.intersectPlane(vS,i.target))))}else if(i.object.isOrthographicCamera){const Cn=i.object.zoom;i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/c)),Cn!==i.object.zoom&&(i.object.updateProjectionMatrix(),Xr=!0)}return c=1,E=!1,Xr||Ua||Pe.distanceToSquared(i.object.position)>a||8*(1-Ve.dot(i.object.quaternion))>a||jt.distanceToSquared(i.target)>a?(i.dispatchEvent(AS),Pe.copy(i.object.position),Ve.copy(i.object.quaternion),jt.copy(i.target),!0):!1}})(),this.stopDamping=function(){l.set(0,0,0),h.set(0,0,0)},this.dispose=function(){i.domElement.removeEventListener("contextmenu",qe),i.domElement.removeEventListener("pointerdown",J),i.domElement.removeEventListener("pointercancel",ue),i.domElement.removeEventListener("wheel",be),i.domElement.removeEventListener("pointermove",le),i.domElement.removeEventListener("pointerup",ue),i.domElement.getRootNode().removeEventListener("keydown",at,{capture:!0}),i._domElementKeyEvents!==null&&(i._domElementKeyEvents.removeEventListener("keydown",Ne),i._domElementKeyEvents=null)};const i=this,n={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=n.NONE;const a=1e-6,o=new pa,l=new pa(0,0,0);let c=1;const h=new x,u=new $,d=new $,p=new $,m=new $,A=new $,g=new $,y=new $,_=new $,v=new $,b=new x,T=new $;let E=!1;const M=[],S={};let w=!1;function C(I){return I!==null?2*Math.PI/60*i.autoRotateSpeed*I:2*Math.PI/60/60*i.autoRotateSpeed}function D(I){return i.enableDamping&&!i.zoomToCursor&&!i.object.isOrthographicCamera?1:Math.pow(.95,i.zoomSpeed)}function O(I){l.theta-=I}function F(I){l.phi-=I}this.rotateUp=F,this.rotateLeft=O;const G=(function(){const I=new x;return function(X,Pe){I.setFromMatrixColumn(Pe,0),I.multiplyScalar(-X),h.add(I)}})(),j=(function(){const I=new x;return function(X,Pe){i.screenSpacePanning===!0?I.setFromMatrixColumn(Pe,1):(I.setFromMatrixColumn(Pe,0),I.crossVectors(i.object.up,I)),I.multiplyScalar(X),h.add(I)}})(),W=(function(){const I=new x;return function(X,Pe){const Ve=i.domElement;if(i.object.isPerspectiveCamera){const jt=i.object.position;I.copy(jt).sub(i.target);let Ot=I.length();Ot*=Math.tan(i.object.fov/2*Math.PI/180),G(2*X*Ot/Ve.clientHeight,i.object.matrix),j(2*Pe*Ot/Ve.clientHeight,i.object.matrix)}else i.object.isOrthographicCamera?(G(X*(i.object.right-i.object.left)/i.object.zoom/Ve.clientWidth,i.object.matrix),j(Pe*(i.object.top-i.object.bottom)/i.object.zoom/Ve.clientHeight,i.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}})();function K(I,ie=0){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?(c/=I,l.radius=Math.max(-i.maxZoomSpeed,Math.min(i.maxZoomSpeed,l.radius-ie))):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function q(I,ie=0){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?(c*=I,l.radius=Math.max(-i.maxZoomSpeed,Math.min(i.maxZoomSpeed,l.radius+ie))):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}this.zoomIn=function(I){K(1,I*i.zoomSpeed)},this.zoomOut=function(I){q(1,I*i.zoomSpeed)};function oe(I,ie){if(!i.zoomToCursor)return;E=!0;const X=i.domElement.getBoundingClientRect(),Pe=I-X.left,Ve=ie-X.top,jt=X.width,Ot=X.height;T.x=Pe/jt*2-1,T.y=-(Ve/Ot)*2+1,b.set(T.x,T.y,1).unproject(i.object).sub(i.object.position).normalize()}function re(I){return Math.max(i.minDistance,Math.min(i.maxDistance,I))}function Ce(I){u.set(I.clientX,I.clientY)}function Ie(I){oe(I.clientX,I.clientX),y.set(I.clientX,I.clientY)}function Ue(I){m.set(I.clientX,I.clientY)}function te(I){d.set(I.clientX,I.clientY),p.subVectors(d,u).multiplyScalar(i.rotateSpeed);const ie=i.domElement;O(2*Math.PI*p.x/ie.clientHeight),F(2*Math.PI*p.y/ie.clientHeight),u.copy(d),i.update()}function ce(I){_.set(I.clientX,I.clientY),v.subVectors(_,y),v.y>0?K(D(v.y)):v.y<0&&q(D(v.y)),y.copy(_),i.update()}function me(I){A.set(I.clientX,I.clientY),g.subVectors(A,m).multiplyScalar(i.panSpeed),W(g.x,g.y),m.copy(A),i.update()}function we(I){oe(I.clientX,I.clientY);let ie=0;switch(I.deltaMode){case 2:ie+=I.deltaY*1;break;case 1:ie+=I.deltaY*.4;break;default:ie+=I.deltaY*.01;break}I.deltaY<0?i.zoomToCursor||i.object.isOrthographicCamera?q(D()):q(1,ie*i.zoomSpeed):I.deltaY>0&&(i.zoomToCursor||i.object.isOrthographicCamera?K(D()):K(1,-ie*i.zoomSpeed)),i.update()}function je(I){let ie=!1;switch(I.code){case i.keys.UP:I.ctrlKey||I.metaKey||I.shiftKey?F(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):W(0,i.keyPanSpeed),ie=!0;break;case i.keys.BOTTOM:I.ctrlKey||I.metaKey||I.shiftKey?F(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):W(0,-i.keyPanSpeed),ie=!0;break;case i.keys.LEFT:I.ctrlKey||I.metaKey||I.shiftKey?O(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):W(i.keyPanSpeed,0),ie=!0;break;case i.keys.RIGHT:I.ctrlKey||I.metaKey||I.shiftKey?O(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):W(-i.keyPanSpeed,0),ie=!0;break}ie&&(I.preventDefault(),i.update())}function ht(I){if(M.length===1)u.set(I.pageX,I.pageY);else{const ie=Nt(I),X=.5*(I.pageX+ie.x),Pe=.5*(I.pageY+ie.y);u.set(X,Pe)}}function Ze(I){if(M.length===1)m.set(I.pageX,I.pageY);else{const ie=Nt(I),X=.5*(I.pageX+ie.x),Pe=.5*(I.pageY+ie.y);m.set(X,Pe)}}function Y(I){const ie=Nt(I),X=I.pageX-ie.x,Pe=I.pageY-ie.y,Ve=Math.sqrt(X*X+Pe*Pe);y.set(0,Ve)}function fe(I){i.enableZoom&&Y(I),i.enablePan&&Ze(I)}function he(I){i.enableZoom&&Y(I),i.enableRotate&&ht(I)}function Se(I){if(M.length==1)d.set(I.pageX,I.pageY);else{const X=Nt(I),Pe=.5*(I.pageX+X.x),Ve=.5*(I.pageY+X.y);d.set(Pe,Ve)}p.subVectors(d,u).multiplyScalar(i.rotateSpeed);const ie=i.domElement;O(2*Math.PI*p.x/ie.clientHeight),F(2*Math.PI*p.y/ie.clientHeight),u.copy(d)}function Ee(I){if(M.length===1)A.set(I.pageX,I.pageY);else{const ie=Nt(I),X=.5*(I.pageX+ie.x),Pe=.5*(I.pageY+ie.y);A.set(X,Pe)}g.subVectors(A,m).multiplyScalar(i.panSpeed),W(g.x,g.y),m.copy(A)}function De(I){const ie=Nt(I),X=I.pageX-ie.x,Pe=I.pageY-ie.y,Ve=Math.sqrt(X*X+Pe*Pe);_.set(0,Ve),v.set(0,Math.pow(_.y/y.y,i.zoomSpeed*6)),K(v.y),y.copy(_);const jt=(I.pageX+ie.x)*.5,Ot=(I.pageY+ie.y)*.5;oe(jt,Ot)}function N(I){i.enableZoom&&De(I),i.enablePan&&Ee(I)}function B(I){i.enableZoom&&De(I),i.enableRotate&&Se(I)}function J(I){i.enabled!==!1&&(M.length===0&&(i.domElement.setPointerCapture(I.pointerId),i.domElement.addEventListener("pointermove",le),i.domElement.addEventListener("pointerup",ue)),!Mt(I)&&(Ft(I),I.pointerType==="touch"?dt(I):ve(I)))}function le(I){i.enabled!==!1&&(I.pointerType==="touch"?We(I):I.buttons?Ke(I):ue(I))}function ue(I){switch(yt(I),M.length){case 0:i.domElement.releasePointerCapture(I.pointerId),i.domElement.removeEventListener("pointermove",le),i.domElement.removeEventListener("pointerup",ue),i.dispatchEvent(yS),s=n.NONE;break;case 1:const ie=M[0],X=S[ie];dt({pointerId:ie,pageX:X.x,pageY:X.y});break}}function ve(I){let ie;switch(I.button){case 0:ie=i.mouseButtons.LEFT;break;case 1:ie=i.mouseButtons.MIDDLE;break;case 2:ie=i.mouseButtons.RIGHT;break;default:ie=-1}switch(ie){case zl.DOLLY:if(i.enableZoom===!1)return;Ie(I),s=n.DOLLY;break;case zl.ROTATE:if(I.ctrlKey||I.metaKey||I.shiftKey){if(i.enablePan===!1)return;Ue(I),s=n.PAN}else{if(i.enableRotate===!1)return;Ce(I),s=n.ROTATE}break;case zl.PAN:if(I.ctrlKey||I.metaKey||I.shiftKey){if(i.enableRotate===!1)return;Ce(I),s=n.ROTATE}else{if(i.enablePan===!1)return;Ue(I),s=n.PAN}break;default:s=n.NONE}s!==n.NONE&&i.dispatchEvent(av)}function Ke(I){switch(s){case n.ROTATE:if(i.enableRotate===!1)return;te(I);break;case n.DOLLY:if(i.enableZoom===!1)return;ce(I);break;case n.PAN:if(i.enablePan===!1)return;me(I);break}}function be(I){i.enabled===!1||i.enableZoom===!1||s!==n.NONE||(I.preventDefault(),i.dispatchEvent(av),we(Ye(I)),i.dispatchEvent(yS))}function Ye(I){const ie=I.deltaMode,X={clientX:I.clientX,clientY:I.clientY,deltaY:I.deltaY};switch(ie){case 1:X.deltaY*=16;break;case 2:X.deltaY*=100;break}return I.ctrlKey&&!w&&(X.deltaY*=10),X}function at(I){I.key==="Control"&&(w=!0,i.domElement.getRootNode().addEventListener("keyup",Be,{passive:!0,capture:!0}))}function Be(I){I.key==="Control"&&(w=!1,i.domElement.getRootNode().removeEventListener("keyup",Be,{passive:!0,capture:!0}))}function Ne(I){i.enabled===!1||i.enablePan===!1||je(I)}function dt(I){switch(Qt(I),M.length){case 1:switch(i.touches.ONE){case Vl.ROTATE:if(i.enableRotate===!1)return;ht(I),s=n.TOUCH_ROTATE;break;case Vl.PAN:if(i.enablePan===!1)return;Ze(I),s=n.TOUCH_PAN;break;default:s=n.NONE}break;case 2:switch(i.touches.TWO){case Vl.DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;fe(I),s=n.TOUCH_DOLLY_PAN;break;case Vl.DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;he(I),s=n.TOUCH_DOLLY_ROTATE;break;default:s=n.NONE}break;default:s=n.NONE}s!==n.NONE&&i.dispatchEvent(av)}function We(I){switch(Qt(I),s){case n.TOUCH_ROTATE:if(i.enableRotate===!1)return;Se(I),i.update();break;case n.TOUCH_PAN:if(i.enablePan===!1)return;Ee(I),i.update();break;case n.TOUCH_DOLLY_PAN:if(i.enableZoom===!1&&i.enablePan===!1)return;N(I),i.update();break;case n.TOUCH_DOLLY_ROTATE:if(i.enableZoom===!1&&i.enableRotate===!1)return;B(I),i.update();break;default:s=n.NONE}}function qe(I){i.enabled!==!1&&I.preventDefault()}function Ft(I){M.push(I.pointerId)}function yt(I){delete S[I.pointerId];for(let ie=0;ie<M.length;ie++)if(M[ie]==I.pointerId){M.splice(ie,1);return}}function Mt(I){for(let ie=0;ie<M.length;ie++)if(M[ie]==I.pointerId)return!0;return!1}function Qt(I){let ie=S[I.pointerId];ie===void 0&&(ie=new $,S[I.pointerId]=ie),ie.set(I.pageX,I.pageY)}function Nt(I){const ie=I.pointerId===M[0]?M[1]:M[0];return S[ie]}i.domElement.addEventListener("contextmenu",qe),i.domElement.addEventListener("pointerdown",J),i.domElement.addEventListener("pointercancel",ue),i.domElement.addEventListener("wheel",be,{passive:!1}),i.domElement.getRootNode().addEventListener("keydown",at,{passive:!0,capture:!0}),this.update()}}var cF=Object.defineProperty,hF=Object.getOwnPropertyDescriptor,ci=(r,e,t,i)=>{for(var n=i>1?void 0:i?hF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&cF(e,t,n),n};f.OrbitControls3=class extends ov{constructor(){super(...arguments),this.type="OrbitControls",this.enabled=!0,this.dollyZoom=!1,this.zoomToCursor=!1,this.enableDamping=!0,this.dampingFactor=.08,this.autoRotate=!1,this.autoRotateSpeed=2,this.enableZoom=!0,this.zoomSpeed=.15,this.maxZoomSpeed=.2,this.enableRotate=!0,this.rotateSpeed=2,this.enablePan=!0,this.panSpeed=1,this.autoPushTarget=!1,this.autoPullTarget=!1,this.minDistance=.35,this.maxDistance=1e6,this.minZoom=.01,this.maxZoom=1e6,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1e6,this.maxAzimuthAngle=1e6,this.clampMin=new x(-1e6,-1e6,-1e6),this.clampMax=new x(1e6,1e6,1e6),this.screenSpacePanning=!0,this.keyPanSpeed=7,this.throttleUpdate=60}},ci([z()],f.OrbitControls3.prototype,"type",2),ci([ae()],f.OrbitControls3.prototype,"enabled",2),ci([ae(),z()],f.OrbitControls3.prototype,"dollyZoom",2),ci([ae(),z()],f.OrbitControls3.prototype,"zoomToCursor",2),ci([ae(),z()],f.OrbitControls3.prototype,"enableDamping",2),ci([Fe(),z()],f.OrbitControls3.prototype,"dampingFactor",2),ci([ae(),z()],f.OrbitControls3.prototype,"autoRotate",2),ci([Fe(),z()],f.OrbitControls3.prototype,"autoRotateSpeed",2),ci([ae(),z()],f.OrbitControls3.prototype,"enableZoom",2),ci([Fe(),z()],f.OrbitControls3.prototype,"zoomSpeed",2),ci([Fe(),z()],f.OrbitControls3.prototype,"maxZoomSpeed",2),ci([ae(),z()],f.OrbitControls3.prototype,"enableRotate",2),ci([Fe(),z()],f.OrbitControls3.prototype,"rotateSpeed",2),ci([ae(),z()],f.OrbitControls3.prototype,"enablePan",2),ci([Fe(),z()],f.OrbitControls3.prototype,"panSpeed",2),ci([Fe(),z()],f.OrbitControls3.prototype,"autoPushTarget",2),ci([Fe(),z()],f.OrbitControls3.prototype,"autoPullTarget",2),ci([Fe(),z()],f.OrbitControls3.prototype,"minDistance",2),ci([Fe(),z()],f.OrbitControls3.prototype,"maxDistance",2),ci([Fe(),z()],f.OrbitControls3.prototype,"minZoom",2),ci([Fe(),z()],f.OrbitControls3.prototype,"maxZoom",2),ci([Fe(),z()],f.OrbitControls3.prototype,"minPolarAngle",2),ci([Fe(),z()],f.OrbitControls3.prototype,"maxPolarAngle",2),ci([Fe(),z()],f.OrbitControls3.prototype,"minAzimuthAngle",2),ci([Fe(),z()],f.OrbitControls3.prototype,"maxAzimuthAngle",2),ci([gi(),z()],f.OrbitControls3.prototype,"clampMin",2),ci([gi(),z()],f.OrbitControls3.prototype,"clampMax",2),ci([z()],f.OrbitControls3.prototype,"screenSpacePanning",2),ci([z()],f.OrbitControls3.prototype,"keyPanSpeed",2),f.OrbitControls3=ci([Aa("Orbit Controls")],f.OrbitControls3);const ro=new Uu;ro.params.Line2={threshold:.01};const Xn=new x,ao=new x,Mi=new Qe,_S={X:new x(1,0,0),Y:new x(0,1,0),Z:new x(0,0,1)},lv={type:"change"},bS={type:"mouseDown",mode:null},wS={type:"mouseUp",mode:null},CS={type:"objectChange"};class cr extends ft{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const i=new MS;this._gizmo=i,this.add(i);const n=new TS;this._plane=n,this.add(n);const s=this;function a(_,v){let b=v;Object.defineProperty(s,_,{get:function(){return b!==void 0?b:v},set:function(T){b!==T&&!(s.lockProps&&s.lockProps.includes(_))&&(b=T,n[_]=T,i[_]=T,s.dispatchEvent({type:_+"-changed",value:T}),s.dispatchEvent(lv))}}),s[_]=v,n[_]=v,i[_]=v}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0);const o=new x,l=new x,c=new Qe,h=new Qe,u=new x,d=new Qe,p=new x,m=new x,A=new x,g=0,y=new x;a("worldPosition",o),a("worldPositionStart",l),a("worldQuaternion",c),a("worldQuaternionStart",h),a("cameraPosition",u),a("cameraQuaternion",d),a("pointStart",p),a("pointEnd",m),a("rotationAxis",A),a("rotationAngle",g),a("eye",y),this._offset=new x,this._startNorm=new x,this._endNorm=new x,this._cameraScale=new x,this._parentPosition=new x,this._parentQuaternion=new Qe,this._parentQuaternionInv=new Qe,this._parentScale=new x,this._worldScaleStart=new x,this._worldQuaternionInv=new Qe,this._worldScale=new x,this._positionStart=new x,this._quaternionStart=new Qe,this._scaleStart=new x,this._getPointer=uF.bind(this),this._onPointerDown=fF.bind(this),this._onPointerHover=dF.bind(this),this._onPointerMove=pF.bind(this),this._onPointerUp=mF.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&ro.setFromCamera(e,this.camera);const t=cv(this._gizmo.picker[this.mode],ro);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&ro.setFromCamera(e,this.camera);const t=cv(this._plane,ro,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,bS.mode=this.mode,this.dispatchEvent(bS)}}pointerMove(e){const t=this.axis,i=this.mode,n=this.object,s=n&&n.userData&&n.userData.isMultiSelectDummy;let a=s?"world":this.space;if(i==="scale"&&!s?a="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(a="world"),n===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&ro.setFromCamera(e,this.camera);const o=cv(this._plane,ro,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),a==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),a==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),n.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(a==="local"&&(n.position.applyQuaternion(Mi.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.position.applyQuaternion(this._quaternionStart)),a==="world"&&(n.parent&&n.position.add(Xn.setFromMatrixPosition(n.parent.matrixWorld)),t.search("X")!==-1&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.parent&&n.position.sub(Xn.setFromMatrixPosition(n.parent.matrixWorld))));else if(i==="scale"){if(t.search("XYZ")!==-1){let l=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(l*=-1),ao.set(l,l,l)}else Xn.copy(this.pointStart),ao.copy(this.pointEnd),Xn.applyQuaternion(this._worldQuaternionInv),ao.applyQuaternion(this._worldQuaternionInv),ao.divide(Xn),t.search("X")===-1&&(ao.x=1),t.search("Y")===-1&&(ao.y=1),t.search("Z")===-1&&(ao.z=1);n.scale.copy(this._scaleStart).multiply(ao),this.scaleSnap&&(t.search("X")!==-1&&(n.scale.x=Math.round(n.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(n.scale.y=Math.round(n.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(n.scale.z=Math.round(n.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const l=20/this.worldPosition.distanceTo(Xn.setFromMatrixPosition(this.camera.matrixWorld));let c=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Xn.copy(this.rotationAxis).cross(this.eye))*l):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(_S[t]),Xn.copy(_S[t]),a==="local"&&Xn.applyQuaternion(this.worldQuaternion),Xn.cross(this.eye),Xn.length()===0?c=!0:this.rotationAngle=this._offset.dot(Xn.normalize())*l),(t==="E"||c)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),a==="local"&&t!=="E"&&t!=="XYZE"?(n.quaternion.copy(this._quaternionStart),n.quaternion.multiply(Mi.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),n.quaternion.copy(Mi.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),n.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(lv),this.dispatchEvent(CS)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&(wS.mode=this.mode,this.dispatchEvent(wS)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.dragging=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(lv),this.dispatchEvent(CS),this.pointStart.copy(this.pointEnd))}getRaycaster(){return ro}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}cr.ObjectConstructors={MeshBasicMaterial:ss,LineBasicMaterial:Ei};function uF(r){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:r.button,buttons:r.buttons};{const e=this.domElement.getBoundingClientRect();return{x:(r.clientX-e.left)/e.width*2-1,y:-(r.clientY-e.top)/e.height*2+1,button:r.button,buttons:r.buttons}}}function dF(r){if(this.enabled)switch(r.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(r));break}}function fF(r){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(r)),this.pointerDown(this._getPointer(r)))}function pF(r){this.enabled&&this.pointerMove(this._getPointer(r))}function mF(r){this.enabled&&(this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(r)))}function cv(r,e,t){const i=e.intersectObject(r,!0);for(let n=0;n<i.length;n++)if(i[n].object.visible||t)return i[n];return!1}const tm=new Tt,Ai=new x(0,1,0),xS=new x(0,0,0),SS=new pe,im=new Qe,nm=new Qe,Br=new x,ES=new pe,qu=new x(1,0,0),ul=new x(0,1,0),Xu=new x(0,0,1),sm=new x,Yu=new x,$u=new x;class MS extends ft{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new cr.ObjectConstructors.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new cr.ObjectConstructors.LineBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const n=t.clone();n.opacity=1;const s=e.clone();s.color.setHex(15663205),s.opacity=.95;const a=e.clone();a.color.setHex(2014720),a.opacity=.95;const o=e.clone();o.color.setHex(37885),o.opacity=.95;const l=e.clone();l.color.setHex(16618689),l.__color=s.color.getHex();const c=e.clone();c.color.setHex(12516474),c.__color=a.color.getHex();const h=e.clone();h.color.setHex(11397372),h.__color=o.color.getHex();const u=e.clone();u.color.setHex(15663205),u.opacity=.75;const d=e.clone();d.color.setHex(2014720),d.opacity=.75;const p=e.clone();p.color.setHex(37885),p.opacity=.75;const m=e.clone();m.color.setHex(12893629),m.opacity=.75;const A=e.clone();A.color.setHex(16777051),A.opacity=.25;const g=e.clone();g.color.setHex(7895160),g.opacity=.75;const y=new sn(0,.04,.1,12);y.translate(0,.05,0);const _=new mi(.08,.08,.08);_.translate(0,.04,0);const v=new $e;v.setAttribute("position",new Me([0,0,0,1,0,0],3));const b=new sn(.0075,.0075,.5,3);b.translate(0,.25,0);function T(q,oe){const re=new $a(q,.0075,3,64,oe*Math.PI*2);return re.rotateY(Math.PI/2),re.rotateX(Math.PI/2),re}function E(q,oe){const re=new $a(q,.1,4,24,oe*Math.PI*2);return re.rotateY(Math.PI/2),re.rotateX(Math.PI/2),re}function M(){const q=new $e;return q.setAttribute("position",new Me([0,0,0,1,1,1],3)),q}const S={X:[[new ye(y,l),[.5,0,0],[0,0,-Math.PI/2]],[new ye(b,s),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ye(y,c),[0,.5,0]],[new ye(b,a)]],Z:[[new ye(y,h),[0,0,.5],[Math.PI/2,0,0]],[new ye(b,o),null,[Math.PI/2,0,0]]],XYZ:[[new ye(new da(.1,2),m.clone()),[0,0,0]]],XY:[[new ye(new mi(.2,.2,.01),p.clone()),[.2,.2,0]]],YZ:[[new ye(new mi(.2,.2,.01),u.clone()),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new ye(new mi(.2,.2,.01),d.clone()),[.2,0,.2],[-Math.PI/2,0,0]]]},w={X:[[new ye(new sn(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]]],Y:[[new ye(new sn(.2,0,.6,4),i),[0,.3,0]]],Z:[[new ye(new sn(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]]],XYZ:[[new ye(new da(.2,0),i)]],XY:[[new ye(new mi(.25,.25,.01),i),[.2,.2,0]]],YZ:[[new ye(new mi(.25,.25,.01),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new ye(new mi(.25,.25,.01),i),[.2,0,.2],[-Math.PI/2,0,0]]]},C={START:[[new ye(new da(.01,2),n),null,null,null,"helper"]],END:[[new ye(new da(.01,2),n),null,null,null,"helper"]],DELTA:[[new fn(M(),n),null,null,null,"helper"]],X:[[new fn(v,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new fn(v,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new fn(v,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},D={XYZE:[[new ye(new Ds(.1,10,8),m)],[new ye(T(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new ye(T(.5,.5),s)],[new ye(b,s),[0,0,0],[0,0,-Math.PI/2]],[new ye(y.clone().translate(.5,0,0),l),[0,0,0],[-Math.PI/2,-Math.PI/2,-Math.PI/2]]],Y:[[new ye(T(.5,.5),a),null,[0,0,-Math.PI/2]],[new ye(b,a)],[new ye(y.clone().rotateZ(-Math.PI/2).translate(0,.5,0),c),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ye(T(.5,.5),o),null,[0,Math.PI/2,0]],[new ye(b,o),null,[Math.PI/2,0,0]],[new ye(y.clone().rotateZ(-Math.PI).translate(0,0,.5),h),[0,0,0],[0,Math.PI/2,0]]]},O={AXIS:[[new fn(v,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},F={XYZE:[[new ye(new Ds(.25,10,8),i)]],X:[[new ye(E(.5,.5),i)]],Y:[[new ye(E(.5,.5),i),[0,0,0],[0,0,-Math.PI/2]]],Z:[[new ye(E(.5,.5),i),[0,0,0],[0,Math.PI/2,0]]]},G={X:[[new ye(_,l),[.5,0,0],[0,0,-Math.PI/2]],[new ye(b,s),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ye(_,c),[0,.5,0]],[new ye(b,a)]],Z:[[new ye(_,h),[0,0,.5],[Math.PI/2,0,0]],[new ye(b,o),[0,0,0],[Math.PI/2,0,0]]],XY:[[new ye(new mi(.15,.15,.01),p),[.15,.15,0]]],YZ:[[new ye(new mi(.15,.15,.01),u),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ye(new mi(.15,.15,.01),d),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ye(new mi(.1,.1,.1),m.clone())]]},j={X:[[new ye(new sn(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new ye(new sn(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ye(new sn(.2,0,.6,4),i),[0,.3,0]],[new ye(new sn(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ye(new sn(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new ye(new sn(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ye(new mi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new ye(new mi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ye(new mi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ye(new mi(.2,.2,.2),i),[0,0,0]]]},W={X:[[new fn(v,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new fn(v,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new fn(v,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function K(q){const oe=new ft;for(const re in q)for(let Ce=q[re].length;Ce--;){const Ie=q[re][Ce][0].clone(),Ue=q[re][Ce][1],te=q[re][Ce][2],ce=q[re][Ce][3],me=q[re][Ce][4];Ie.name=re,Ie.tag=me,Ue&&Ie.position.set(Ue[0],Ue[1],Ue[2]),te&&Ie.rotation.set(te[0],te[1],te[2]),ce&&Ie.scale.set(ce[0],ce[1],ce[2]),Ie.updateMatrix();const we=Ie.geometry.clone();we.applyMatrix4(Ie.matrix),Ie.geometry=we,Ie.renderOrder=1/0,Ie.position.set(0,0,0),Ie.rotation.set(0,0,0),Ie.scale.set(1,1,1),oe.add(Ie)}return oe}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=K(S)),this.add(this.gizmo.rotate=K(D)),this.add(this.gizmo.scale=K(G)),this.add(this.picker.translate=K(w)),this.add(this.picker.rotate=K(F)),this.add(this.picker.scale=K(j)),this.add(this.helper.translate=K(C)),this.add(this.helper.rotate=K(O)),this.add(this.helper.scale=K(W)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t=this.object&&this.object.userData&&this.object.userData.isMultiSelectDummy,n=(this.mode==="scale"&&!t?"local":t?"world":this.space)==="local"?this.worldQuaternion:nm;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let a=0;a<s.length;a++){const o=s[a];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let l;if(this.camera.isOrthographicCamera?l=(this.camera.top-this.camera.bottom)/this.camera.zoom:l=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(l*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&(Mi.setFromEuler(tm.set(0,0,0)),o.quaternion.copy(n).multiply(Mi),Math.abs(Ai.copy(qu).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(Mi.setFromEuler(tm.set(0,0,Math.PI/2)),o.quaternion.copy(n).multiply(Mi),Math.abs(Ai.copy(ul).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(Mi.setFromEuler(tm.set(0,Math.PI/2,0)),o.quaternion.copy(n).multiply(Mi),Math.abs(Ai.copy(Xu).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(Mi.setFromEuler(tm.set(0,Math.PI/2,0)),Ai.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(SS.lookAt(xS,Ai,ul)),o.quaternion.multiply(Mi),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),Xn.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Xn.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(Xn),o.visible=this.dragging):(o.quaternion.copy(n),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(n),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(Ai.copy(qu).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(Ai.copy(ul).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(Ai.copy(Xu).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(Ai.copy(Xu).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(Ai.copy(qu).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(Ai.copy(ul).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(im.copy(n),Ai.copy(this.eye).applyQuaternion(Mi.copy(n).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(SS.lookAt(this.eye,xS,ul)),o.name==="X"&&(Mi.setFromAxisAngle(qu,Math.atan2(-Ai.y,Ai.z)),Mi.multiplyQuaternions(im,Mi),o.quaternion.copy(Mi)),o.name==="Y"&&(Mi.setFromAxisAngle(ul,Math.atan2(Ai.x,Ai.z)),Mi.multiplyQuaternions(im,Mi),o.quaternion.copy(Mi)),o.name==="Z"&&(Mi.setFromAxisAngle(Xu,Math.atan2(Ai.y,Ai.x)),Mi.multiplyQuaternions(im,Mi),o.quaternion.copy(Mi))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis||this.axis.split("").some(function(c){return o.name===c}))&&(o.material.__color&&o.material.color.setHex(o.material.__color),o.material.opacity=1)}super.updateMatrixWorld(e)}}class TS extends ye{constructor(){super(new Er(1e5,1e5,2,2),new cr.ObjectConstructors.MeshBasicMaterial({visible:!1,wireframe:!0,side:Zi,transparent:!0,opacity:.1,toneMapped:!1,allowOverride:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){const t=this.object&&this.object.userData&&this.object.userData.isMultiSelectDummy;let i=t?"world":this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&!t&&(i="local"),sm.copy(qu).applyQuaternion(i==="local"?this.worldQuaternion:nm),Yu.copy(ul).applyQuaternion(i==="local"?this.worldQuaternion:nm),$u.copy(Xu).applyQuaternion(i==="local"?this.worldQuaternion:nm),Ai.copy(Yu),this.mode){case"translate":case"scale":switch(this.axis){case"X":Ai.copy(this.eye).cross(sm),Br.copy(sm).cross(Ai);break;case"Y":Ai.copy(this.eye).cross(Yu),Br.copy(Yu).cross(Ai);break;case"Z":Ai.copy(this.eye).cross($u),Br.copy($u).cross(Ai);break;case"XY":Br.copy($u);break;case"YZ":Br.copy(sm);break;case"XZ":Ai.copy($u),Br.copy(Yu);break;case"XYZ":case"E":Br.set(0,0,0);break}break;case"rotate":default:Br.set(0,0,0)}Br.length()===0?this.quaternion.copy(this.cameraQuaternion):(ES.lookAt(Xn.set(0,0,0),Br,Ai),this.quaternion.setFromRotationMatrix(ES)),super.updateMatrixWorld(e)}}function IS(r,e){if(r.metaKey||r.ctrlKey||r.target?.tagName==="TEXTAREA"||r.target?.tagName==="INPUT")return!1;switch(r.code){case"KeyQ":return e.toggleSpace(),!0;case"Equal":case"NumpadAdd":return e.adjustSize(.1),!0;case"Minus":case"NumpadSubtract":return e.adjustSize(-.1),!0;case"KeyX":return e.toggleAxis(0),!0;case"KeyY":return e.toggleAxis(1),!0;case"KeyZ":return e.toggleAxis(2),!0;case"Space":return e.toggleEnabled(),!0;default:return!1}}const rm=new x,PS=new x;function DS(r,e,t,i){const n=e.dot(e),s=e.dot(r)-e.dot(t),a=e.dot(i);return a===0?-s/n:(rm.copy(i).multiplyScalar(n/a).sub(e),PS.copy(i).multiplyScalar(s/a).add(t).sub(r),-rm.dot(PS)/rm.dot(rm))}function gF(r,e,t){const i=Math.abs(r.x)>=Math.abs(r.y)&&Math.abs(r.x)>=Math.abs(r.z)?0:Math.abs(r.y)>=Math.abs(r.x)&&Math.abs(r.y)>=Math.abs(r.z)?1:2,n=[0,1,2].sort((m,A)=>Math.abs(e.getComponent(A))-Math.abs(e.getComponent(m))),s=i===n[0]?n[1]:n[0],a=r.getComponent(i),o=r.getComponent(s),l=e.getComponent(i),c=e.getComponent(s),h=t.getComponent(i),d=(t.getComponent(s)-h*(o/a))/(c-l*(o/a));return[(h-d*l)/a,d]}const RS=new pe,BS=new pe,hv=new pe,LS=new pe,OS=new pe,uv=new pe,US=new pe,AF=new pe,am=new pe,om=new pe,dv=new pe,fv=new $,pv=new x,mv=new x,FS=new x,oo=new Ha,lo=new x,Ku=new x(0,1,0),Ju=new x(1,0,0),Zu=new x(0,1,0),ed=new x(0,0,1),Qg=class Qg extends Ri{constructor(e,t){super(),this.enabled=!0,this.autoTransform=!0,this.gizmoScale=1.25,this.activeAxes=[!0,!0,!0],this.disableAxes=!1,this.disableSliders=!1,this.disableRotations=!1,this.disableScaling=!1,this.axisColors=[15663205,2014720,37885],this.hoveredColor=16777024,this.handleOpacity=.95,this.space="world",this.translationSnap=.5,this.rotationSnap=15,this.scaleSnap=.1,this.depthTest=!1,this.fixed=!0,this.uniformScaleEnabled=!0,this.annotations=!0,this._handles=[],this._raycaster=new Uu,this._activeHandle=null,this._dragging=!1,this._hoveredHandle=null,this._translation=[0,0,0],this._uniformScaling=!1,this._annotationEl=null,this.camera=e,this.domElement=t,this._gizmoGroup=new Ri,this.add(this._gizmoGroup),this._buildHandles(),this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this),t.addEventListener("pointerdown",this._onPointerDown),t.addEventListener("pointermove",this._onPointerMove),t.addEventListener("pointerup",this._onPointerUp),this._onKeyDown=this._handleKeyDown.bind(this),window.addEventListener("keydown",this._onKeyDown)}_handleKeyDown(e){if(!this.enabled||!this.object)return;IS(e,{toggleSpace:()=>{this.space=this.space==="local"?"world":"local"},adjustSize:i=>{this.gizmoScale=Math.max(this.gizmoScale+i,.1)},toggleAxis:i=>{this.activeAxes[i]=!this.activeAxes[i],this.updateHandleVisibility()},toggleEnabled:()=>{this.enabled=!this.enabled}})&&this.dispatchEvent({type:"change"})}_ensureAnnotationEl(){if(!this._annotationEl){const e=document.createElement("div");e.style.cssText="position:absolute;pointer-events:none;display:none;background:#151520;color:white;padding:6px 8px;border-radius:7px;white-space:nowrap;z-index:1000;",this.domElement.parentElement?.appendChild(e),this._annotationEl=e}return this._annotationEl}_showAnnotation(e,t){if(!this.annotations)return;const i=this._ensureAnnotationEl();i.textContent=e,i.style.display="block";const n=t.clone().project(this.camera),s=this.domElement.getBoundingClientRect(),a=(n.x*.5+.5)*s.width,o=(-n.y*.5+.5)*s.height;i.style.left=s.left+a+12+"px",i.style.top=s.top+o-12+"px"}_hideAnnotation(){this._annotationEl&&(this._annotationEl.style.display="none")}_updateAnnotation(e){if(!this.annotations||!this.object)return;const t=["X","Y","Z"];let i="";if(e.type==="arrow")i=`${t[e.axis]}: ${this._translation[e.axis].toFixed(2)}`;else if(e.type==="slider"){const n=(e.axis+1)%3,s=(e.axis+2)%3;i=`${t[n]}: ${this._translation[n].toFixed(2)}, ${t[s]}: ${this._translation[s].toFixed(2)}`}else if(e.type==="rotator"){const n=(e.extraState.angle*180/Math.PI).toFixed(0);i=`${t[e.axis]}: ${n}°`}else e.type==="scaler"&&(i=`${this._uniformScaling?"Uniform":t[e.axis]}: ${e.extraState.scaleCur.toFixed(2)}`);this._showAnnotation(i,this.position)}_buildHandles(){this._handles=[],this._gizmoGroup.clear();const e=Qg.ObjectConstructors,t=1,i=this.depthTest,n=(c,h=this.handleOpacity)=>new e.MeshBasicMaterial({allowOverride:!1,depthTest:i,depthWrite:i,fog:!1,toneMapped:!1,transparent:!0,color:c,opacity:h}),s=()=>new e.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0,opacity:.15,visible:!1}),a=[Ju,Zu,ed];for(let c=0;c<3;c++){const h=n(this.axisColors[c]),u=s(),d=new sn(.0075*t,.0075*t,.5*t,3);d.translate(0,.25*t,0);const p=new ye(d,h);p.renderOrder=500,p.raycast=()=>{};const m=new sn(0,.04*t,.1*t,12);m.translate(0,.05*t,0);const A=new ye(m,h);A.position.set(0,.5*t,0),A.renderOrder=500,A.raycast=()=>{};const g=new sn(.2*t,0,.6*t,4);g.translate(0,.3*t,0);const y=new ye(g,u);y.visible=!1;const _=new Qe().setFromUnitVectors(Ku,a[c]),v=new Ri;v.quaternion.copy(_),v.add(p,A,y),this._gizmoGroup.add(v);const b={type:"arrow",axis:c,gizmoMeshes:[p,A],pickerMeshes:[y],materials:[h],clickInfo:null,extraState:null};y.userData._pivotHandle=b,this._handles.push(b)}const o=[[2,Ju,Zu],[1,ed,Ju],[0,Zu,ed]];for(const[c,h,u]of o){const d=n(this.axisColors[c],.75),p=s(),m=.2*t,A=new mi(m,m,.01*t),g=new ye(A,d);g.renderOrder=500,g.raycast=()=>{};const y=new mi(m*1.25,m*1.25,.01*t),_=new ye(y,p);_.visible=!1;const v=h.clone().normalize(),b=u.clone().normalize(),T=v.clone().cross(b),E=v.clone().multiplyScalar(m).add(b.clone().multiplyScalar(m)),M=new Ri,S=new pe().makeBasis(v,b,T);M.applyMatrix4(S),M.position.copy(E),M.add(g,_),this._gizmoGroup.add(M);const w={type:"slider",axis:c,gizmoMeshes:[g],pickerMeshes:[_],materials:[d],clickInfo:null,extraState:null};_.userData._pivotHandle=w,this._handles.push(w)}const l=[[2,Ju,Zu],[1,ed,Ju],[0,Zu,ed]];for(const[c,h,u]of l){const d=n(this.axisColors[c]),p=s(),m=.5*t,A=new $a(m,.0075*t,3,16,Math.PI/2),g=new ye(A,d);g.renderOrder=500,g.raycast=()=>{};const y=new $a(m,.1*t,4,12,Math.PI/2),_=new ye(y,p);_.visible=!1;const v=h.clone().normalize(),b=u.clone().normalize(),T=v.clone().cross(b),E=new Ri,M=new pe().makeBasis(v,b,T);E.applyMatrix4(M),E.add(g,_),this._gizmoGroup.add(E);const S={type:"rotator",axis:c,gizmoMeshes:[g],pickerMeshes:[_],materials:[d],clickInfo:null,extraState:{angle0:0,angle:0}};_.userData._pivotHandle=S,this._handles.push(S)}for(let c=0;c<3;c++){const h=n(this.axisColors[c]),u=.04*t,d=new Ds(u,12,12),p=new ye(d,h);p.renderOrder=500;const m=new Qe().setFromUnitVectors(Ku,a[c]),A=new Ri;A.quaternion.copy(m),p.position.set(0,.6*t+u,0),A.add(p),this._gizmoGroup.add(A);const g={type:"scaler",axis:c,gizmoMeshes:[p],pickerMeshes:[p],materials:[h],clickInfo:null,extraState:{scale0:1,scaleCur:1}};p.userData._pivotHandle=g,this._handles.push(g)}this.updateHandleVisibility(),this._gizmoGroup.traverse(c=>{c.castShadow=!1,c.receiveShadow=!1,c.userData.__keepShadowDef=!0})}updateHandleVisibility(){if(this._handles)for(const e of this._handles){let t=!0;if(e.type==="arrow")t=!this.disableAxes&&this.activeAxes[e.axis];else if(e.type==="scaler")t=!this.disableScaling&&this.activeAxes[e.axis];else if(e.type==="slider"){const i=[[1,2],[0,2],[0,1]],[n,s]=i[e.axis];t=!this.disableSliders&&this.activeAxes[n]&&this.activeAxes[s]}else if(e.type==="rotator"){const i=[[1,2],[0,2],[0,1]],[n,s]=i[e.axis];t=!this.disableRotations&&this.activeAxes[n]&&this.activeAxes[s]}for(const i of e.gizmoMeshes)i.visible=t;for(const i of e.pickerMeshes)i.parent&&(i.parent.visible=t)}}attach(e){return this.object=e,this.visible=!0,this._translation=[0,0,0],this.updateHandleVisibility(),this.updateMatrixWorld(!0),this.dispatchEvent({type:"change"}),this}detach(){return this._dragging&&this._endDrag(),this.object=void 0,this.visible=!1,this._activeHandle=null,this._hideAnnotation(),this.dispatchEvent({type:"change"}),this}updateGizmoScale(){if(!this.object||!this.visible)return;this.object.updateWorldMatrix(!0,!1);const e=new x().setFromMatrixPosition(this.object.matrixWorld);if(this.position.copy(e),this.space==="local"&&!this.object.userData?.isMultiSelectDummy?this.object.matrixWorld.decompose(pv,this.quaternion,mv):this.quaternion.identity(),this.fixed){pv.copy(e),mv.setFromMatrixPosition(this.camera.matrixWorld);let t;if(this.camera.isOrthographicCamera){const i=this.camera;t=(i.top-i.bottom)/i.zoom}else{const i=this.camera;t=pv.distanceTo(mv)*Math.min(1.9*Math.tan(Math.PI*i.fov/360)/i.zoom,7)}this._gizmoGroup.scale.setScalar(t*this.gizmoScale/4)}else this._gizmoGroup.scale.setScalar(this.gizmoScale);for(const t of this._handles)if(t.type==="scaler"){const i=this._uniformScaling?1.8:1;for(const n of t.gizmoMeshes)n.scale.setScalar(i)}}rebuild(){this._buildHandles()}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),window.removeEventListener("keydown",this._onKeyDown),this._annotationEl&&(this._annotationEl.remove(),this._annotationEl=null)}_getNDC(e){const t=this.domElement.getBoundingClientRect();return fv.x=(e.clientX-t.left)/t.width*2-1,fv.y=-((e.clientY-t.top)/t.height)*2+1,fv}_getAllPickers(){const e=[];for(const t of this._handles)for(const i of t.pickerMeshes)e.push(i);return e}_findHandle(e){let t=e;for(;t;){if(t.userData._pivotHandle)return t.userData._pivotHandle;t=t.parent}return null}_handlePointerDown(e){if(!this.enabled||!this.object||!this.visible)return;this._raycaster.setFromCamera(this._getNDC(e),this.camera);const t=this._raycaster.intersectObjects(this._getAllPickers(),!0);if(t.length===0)return;const i=this._findHandle(t[0].object);i&&(e.stopPropagation(),this._activeHandle=i,this._dragging=!0,RS.copy(this.object.matrix),BS.copy(this.object.matrixWorld),this._onDragStart(i,t[0].point,e),this.domElement.setPointerCapture(e.pointerId),this.dispatchEvent({type:"mouseDown",mode:this._getMode(i)}),this.dispatchEvent({type:"dragging-changed",value:!0}))}_handlePointerMove(e){if(!(!this.enabled||!this.object||!this.visible))if(this._raycaster.setFromCamera(this._getNDC(e),this.camera),this._dragging&&this._activeHandle){const t=this._onDragMove(this._activeHandle,this._raycaster.ray,e);t&&(this._applyTransform(t),this._updateAnnotation(this._activeHandle))}else{const t=this._raycaster.intersectObjects(this._getAllPickers(),!0),i=t.length>0?this._findHandle(t[0].object):null;if(i!==this._hoveredHandle){if(this._hoveredHandle)for(const n of this._hoveredHandle.materials)n.color.set(this.axisColors[this._hoveredHandle.axis]);if(i)for(const n of i.materials)n.color.set(this.hoveredColor);this._hoveredHandle=i,this.dispatchEvent({type:"change"})}}}_handlePointerUp(e){!this._dragging||!this._activeHandle||(e.stopPropagation(),this.domElement.releasePointerCapture(e.pointerId),this._endDrag())}_endDrag(){if(!this._activeHandle)return;this._onDragEnd(this._activeHandle),this._hideAnnotation();const e=this._getMode(this._activeHandle);this._activeHandle=null,this._dragging=!1,this.dispatchEvent({type:"mouseUp",mode:e}),this.dispatchEvent({type:"dragging-changed",value:!1})}_onDragStart(e,t,i){const n=e.gizmoMeshes[0].parent;if(n.updateWorldMatrix(!0,!0),e.type==="arrow"){const s=new pe().extractRotation(n.matrixWorld),a=Ku.clone().applyMatrix4(s).normalize();e.clickInfo={clickPoint:t.clone(),dir:a},e.extraState=this._translation[e.axis]}else if(e.type==="slider"){const s=new x().setFromMatrixColumn(n.matrixWorld,0).normalize(),a=new x().setFromMatrixColumn(n.matrixWorld,1).normalize(),o=new x().setFromMatrixColumn(n.matrixWorld,2).normalize(),l=new x().setFromMatrixPosition(n.matrixWorld),c=new Ts().setFromNormalAndCoplanarPoint(o,l);e.clickInfo={clickPoint:t.clone(),e1:s,e2:a,plane:c},e.extraState={x0:this._translation[(e.axis+1)%3],y0:this._translation[(e.axis+2)%3]}}else if(e.type==="rotator"){const s=new x().setFromMatrixPosition(n.matrixWorld),a=new x().setFromMatrixColumn(n.matrixWorld,2).normalize(),o=new x().setFromMatrixPosition(this.camera.matrixWorld).sub(s).normalize(),l=a.clone().cross(o);l.length()===0&&l.copy(o).cross(Ku),l.normalize();const c=20/s.distanceTo(new x().setFromMatrixPosition(this.camera.matrixWorld));e.clickInfo={clickPoint:t.clone(),origin:s,normal:a,tangent:l,rotSpeed:c},e.extraState={angle:0}}else if(e.type==="scaler"){const s=new pe().extractRotation(n.matrixWorld),a=Ku.clone().applyMatrix4(s).normalize(),o=n.matrixWorld.clone(),l=o.clone().invert();e.clickInfo={clickPoint:t.clone(),dir:a,mPLG:o,mPLGInv:l}}}_onDragMove(e,t,i){if(!e.clickInfo)return null;if(e.type==="arrow"){const{clickPoint:n,dir:s}=e.clickInfo,a=e.extraState,o=this.translationLimits?.[e.axis];let l=DS(n,s,t.origin,t.direction);if(i.shiftKey&&this.translationSnap!==null){const c=this.translationSnap;l=Math.round(l/c)*c}return o&&(o[0]!==void 0&&(l=Math.max(l,o[0]-a)),o[1]!==void 0&&(l=Math.min(l,o[1]-a))),this._translation[e.axis]=a+l,am.makeTranslation(s.x*l,s.y*l,s.z*l),am}else if(e.type==="slider"){const{clickPoint:n,e1:s,e2:a,plane:o}=e.clickInfo,{x0:l,y0:c}=e.extraState;oo.copy(t),oo.intersectPlane(o,lo),oo.direction.negate(),oo.intersectPlane(o,lo),lo.sub(n);let[h,u]=gF(s,a,lo);if(i.shiftKey&&this.translationSnap!==null){const m=this.translationSnap;h=Math.round(h/m)*m,u=Math.round(u/m)*m}const d=this.translationLimits?.[(e.axis+1)%3],p=this.translationLimits?.[(e.axis+2)%3];return d&&(d[0]!==void 0&&(h=Math.max(h,d[0]-l)),d[1]!==void 0&&(h=Math.min(h,d[1]-l))),p&&(p[0]!==void 0&&(u=Math.max(u,p[0]-c)),p[1]!==void 0&&(u=Math.min(u,p[1]-c))),this._translation[(e.axis+1)%3]=l+h,this._translation[(e.axis+2)%3]=c+u,am.makeTranslation(h*s.x+u*a.x,h*s.y+u*a.y,h*s.z+u*a.z),am}else if(e.type==="rotator"){const{clickPoint:n,origin:s,normal:a,tangent:o,rotSpeed:l}=e.clickInfo,c=this.rotationLimits?.[e.axis],h=new Ts().setFromNormalAndCoplanarPoint(a,s);oo.copy(t),oo.intersectPlane(h,lo)||(oo.direction.negate(),oo.intersectPlane(h,lo)),lo.sub(n);let u=lo.dot(o)*l;if(i.shiftKey&&this.rotationSnap!==null){const d=this.rotationSnap*Math.PI/180;u=Math.round(u/d)*d}return c&&(u=Ut.clamp(u,c[0],c[1])),e.extraState.angle=u,om.makeRotationAxis(a,u),FS.copy(s).applyMatrix4(om).sub(s).negate(),om.setPosition(FS),om}else if(e.type==="scaler"){const{clickPoint:n,dir:s,mPLG:a,mPLGInv:o}=e.clickInfo,l=this.scaleLimits?.[e.axis],c=DS(n,s,t.origin,t.direction);let h=Math.pow(2,c*.2);i.shiftKey&&this.scaleSnap!==null&&(h=Math.round(h/this.scaleSnap)*this.scaleSnap,h===0&&(h=this.scaleSnap));const u=this.uniformScaleEnabled&&i.altKey;this._uniformScaling=u;const d=l?l[0]:1e-5;return h=Math.max(h,d/e.extraState.scale0),l&&l[1]!==void 0&&(h=Math.min(h,l[1]/e.extraState.scale0)),e.extraState.scaleCur=e.extraState.scale0*h,u?dv.makeScale(h,h,h):dv.makeScale(1,h,1).premultiply(a).multiply(o),dv}return null}_onDragEnd(e){e.type==="rotator"&&(e.extraState.angle0=e.extraState.angle),e.type==="scaler"&&(e.extraState.scale0=e.extraState.scaleCur),this._uniformScaling=!1,e.clickInfo=null}_applyTransform(e){this.object&&(this.object.parent?hv.copy(this.object.parent.matrixWorld):hv.identity(),LS.copy(hv).invert(),OS.copy(BS).premultiply(e),uv.copy(OS).premultiply(LS),US.copy(RS).invert(),AF.copy(uv).multiply(US),this.autoTransform&&(this.object.matrix.copy(uv),this.object.matrix.decompose(this.object.position,this.object.quaternion,this.object.scale)),this.dispatchEvent({type:"objectChange"}),this.dispatchEvent({type:"change"}))}_getMode(e){return e.type==="arrow"||e.type==="slider"?"translate":e.type==="rotator"?"rotate":e.type==="scaler"?"scale":"unknown"}};Qg.ObjectConstructors={MeshBasicMaterial:ss,LineBasicMaterial:Ei};let Qc=Qg;var yF=Object.defineProperty,vF=Object.getOwnPropertyDescriptor,Yn=(r,e,t,i)=>{for(var n=i>1?void 0:i?vF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&yF(e,t,n),n};const NS=new x,gv=new pa,Av=new x,_F={type:"change"};f.FirstPersonControls2=class extends wi{constructor(e,t){super(),this.enabled=!0,this.enableKeys=!0,this.movementSpeed=1,this.lookSpeed=.005,this.lookVertical=!0,this.autoForward=!1,this.activeLook=!0,this.heightSpeed=!1,this.heightCoef=1,this.heightMin=0,this.heightMax=1,this.constrainVertical=!1,this.verticalMin=0,this.verticalMax=Math.PI,this.mouseDragOn=!1,this.autoSpeedFactor=0,this.pointerX=0,this.pointerY=0,this.moveForward=!1,this.moveBackward=!1,this.moveLeft=!1,this.moveRight=!1,this.moveUp=!1,this.moveDown=!1,this.viewHalfX=0,this.viewHalfY=0,this.lat=0,this.lon=0,this.targetPosition=new x,this._lastTime=-1,this.object=e,this.domElement=t,this.onPointerMove=this.onPointerMove.bind(this),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),this.onContextMenu=this.onContextMenu.bind(this),this.domElement.addEventListener("contextmenu",this.onContextMenu),this.domElement.addEventListener("pointermove",this.onPointerMove),this.domElement.addEventListener("pointerdown",this.onPointerDown),this.domElement.addEventListener("pointerup",this.onPointerUp),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),this.handleResize(),this.setOrientation()}setOrientation(){const e=this.object.quaternion;NS.set(0,0,-1).applyQuaternion(e),gv.setFromVector3(NS),this.lat=90-Ut.radToDeg(gv.phi),this.lon=Ut.radToDeg(gv.theta)}handleResize(){this.domElement===document?(this.viewHalfX=window.innerWidth/2,this.viewHalfY=window.innerHeight/2):(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}onPointerDown(e){if(this.domElement!==document&&this.domElement.focus(),this.activeLook)switch(e.button){case 0:this.moveForward=!0;break;case 2:this.moveBackward=!0;break}this.mouseDragOn=!0}onPointerUp(e){if(this.activeLook)switch(e.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}onPointerMove(e){this.domElement===document?(this.pointerX=e.pageX-this.viewHalfX,this.pointerY=e.pageY-this.viewHalfY):(this.pointerX=e.pageX-this.domElement.offsetLeft-this.viewHalfX,this.pointerY=e.pageY-this.domElement.offsetTop-this.viewHalfY)}onKeyDown(e){if(this.enableKeys)switch(e.code){case"ArrowUp":case"KeyW":this.moveForward=!0;break;case"ArrowLeft":case"KeyA":this.moveLeft=!0;break;case"ArrowDown":case"KeyS":this.moveBackward=!0;break;case"ArrowRight":case"KeyD":this.moveRight=!0;break;case"KeyR":this.moveUp=!0;break;case"KeyF":this.moveDown=!0;break}}onKeyUp(e){if(this.enableKeys)switch(e.code){case"ArrowUp":case"KeyW":this.moveForward=!1;break;case"ArrowLeft":case"KeyA":this.moveLeft=!1;break;case"ArrowDown":case"KeyS":this.moveBackward=!1;break;case"ArrowRight":case"KeyD":this.moveRight=!1;break;case"KeyR":this.moveUp=!1;break;case"KeyF":this.moveDown=!1;break}}lookAt(e,t,i){return e.isVector3?Av.copy(e):t===void 0||i===void 0?console.error("FirstPersonControls2.lookAt: y and z parameters are required"):Av.set(e,t,i),this.object.lookAt(Av),this.setOrientation(),this}update(){const e=Mn(),t=(this._lastTime<0?16:Math.min(e-this._lastTime,1e3))/1e3;if(this._lastTime=e,!this.enabled)return;if(this.heightSpeed){const h=Ut.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=t*(h*this.heightCoef)}else this.autoSpeedFactor=0;const i=t*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(i+this.autoSpeedFactor)),this.moveBackward&&this.object.translateZ(i),this.moveLeft&&this.object.translateX(-i),this.moveRight&&this.object.translateX(i),this.moveUp&&this.object.translateY(i),this.moveDown&&this.object.translateY(-i);let n=t*this.lookSpeed;this.activeLook||(n=0);let s=1;this.constrainVertical&&(s=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.pointerX*n,this.lookVertical&&(this.lat-=this.pointerY*n*s),this.lat=Math.max(-85,Math.min(85,this.lat));let a=Ut.degToRad(90-this.lat);const o=Ut.degToRad(this.lon);this.constrainVertical&&(a=Ut.mapLinear(a,0,Math.PI,this.verticalMin,this.verticalMax));const l=this.object.position;this.targetPosition.setFromSphericalCoords(1,a,o).add(l),this.object.lookAt(this.targetPosition),this.dispatchEvent(_F)}dispose(){this.domElement.removeEventListener("contextmenu",this.onContextMenu),this.domElement.removeEventListener("pointerdown",this.onPointerDown),this.domElement.removeEventListener("pointermove",this.onPointerMove),this.domElement.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}onContextMenu(e){this.enableKeys&&e.preventDefault()}},Yn([z(),ae()],f.FirstPersonControls2.prototype,"enabled",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"enableKeys",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"movementSpeed",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"lookSpeed",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"lookVertical",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"autoForward",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"activeLook",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"heightSpeed",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"heightCoef",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"heightMin",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"heightMax",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"constrainVertical",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"verticalMin",2),Yn([z(),Fe()],f.FirstPersonControls2.prototype,"verticalMax",2),Yn([z(),ae()],f.FirstPersonControls2.prototype,"mouseDragOn",2),f.FirstPersonControls2=Yn([Aa("First Person Controls")],f.FirstPersonControls2);var bF=Object.defineProperty,wF=Object.getOwnPropertyDescriptor,jc=(r,e,t,i)=>{for(var n=i>1?void 0:i?wF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&bF(e,t,n),n};const Wc=new Tt(0,0,0,"YXZ"),qc=new x,CF={type:"change"},xF={type:"lock"},SF={type:"unlock"},kS=Math.PI/2;f.PointerLockControls2=class extends wi{constructor(e,t){super(),this.isLocked=!1,this.enabled=!0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.pointerSpeed=1,this.autoLockOnClick=!0,this._movementX=0,this._movementY=0,this._forwardDirection=new x(0,0,-1),this.domElement=t,this.object=e,this.onElementClick=this.onElementClick.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.onPointerlockChange=this.onPointerlockChange.bind(this),this.onPointerlockError=this.onPointerlockError.bind(this),this.connect()}onElementClick(e){this.isLocked||this.autoLockOnClick&&(e.preventDefault(),this.lock())}onMouseMove(e){this.isLocked&&(this._movementX+=e.movementX||e.mozMovementX||e.webkitMovementX||0,this._movementY+=e.movementY||e.mozMovementY||e.webkitMovementY||0)}onPointerlockChange(){this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(xF),this.isLocked=!0):(this.dispatchEvent(SF),this.isLocked=!1)}onPointerlockError(){console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}connect(){this.domElement.ownerDocument.addEventListener("mousemove",this.onMouseMove),this.domElement.ownerDocument.addEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.addEventListener("pointerlockerror",this.onPointerlockError),this.domElement.addEventListener("click",this.onElementClick)}disconnect(){this.domElement.ownerDocument.removeEventListener("mousemove",this.onMouseMove),this.domElement.ownerDocument.removeEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.removeEventListener("pointerlockerror",this.onPointerlockError),this.domElement.removeEventListener("click",this.onElementClick)}dispose(){this.disconnect()}getDirection(e){return e.copy(this._forwardDirection).applyQuaternion(this.object.quaternion)}moveForward(e){qc.setFromMatrixColumn(this.object.matrix,0),qc.crossVectors(this.object.up,qc),this.object.position.addScaledVector(qc,e)}moveRight(e){qc.setFromMatrixColumn(this.object.matrix,0),this.object.position.addScaledVector(qc,e)}lock(){this.domElement.requestPointerLock()}unlock(){this.domElement.ownerDocument.exitPointerLock()}update(){Math.abs(this._movementX)<1e-4&&Math.abs(this._movementY)<1e-4||(Wc.setFromQuaternion(this.object.quaternion),Wc.y-=this._movementX*.002*this.pointerSpeed,Wc.x-=this._movementY*.002*this.pointerSpeed,this._movementX=0,this._movementY=0,Wc.x=Math.max(kS-this.maxPolarAngle,Math.min(kS-this.minPolarAngle,Wc.x)),this.object.quaternion.setFromEuler(Wc),this.dispatchEvent(CF))}},jc([ae(),z()],f.PointerLockControls2.prototype,"enabled",2),jc([Fe(),z()],f.PointerLockControls2.prototype,"minPolarAngle",2),jc([Fe(),z()],f.PointerLockControls2.prototype,"maxPolarAngle",2),jc([Fe(),z()],f.PointerLockControls2.prototype,"pointerSpeed",2),jc([ae(),z()],f.PointerLockControls2.prototype,"autoLockOnClick",2),f.PointerLockControls2=jc([Aa("Pointer Lock Controls")],f.PointerLockControls2);var EF=Object.defineProperty,MF=Object.getOwnPropertyDescriptor,td=(r,e,t,i)=>{for(var n=i>1?void 0:i?MF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&EF(e,t,n),n};const TF=new x(0,0,1),GS=new Tt,IF=new Qe,PF=new Qe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),Xc=new Qe,DF={type:"change"},RF=1e-6;f.DeviceOrientationControls2=class extends wi{constructor(e){super(),this.enabled=!1,this.lastOrder="XYZ",this.dampingFactor=.05,this.lastQuaternion=new Qe,this.onDeviceOrientationChangeEvent=t=>{this.deviceOrientation=t},this.onScreenOrientationChangeEvent=()=>{this.screenOrientation=screen.orientation},this._initQuaternion=new Qe,this._initQuaternionInvert=new Qe,this._initQuaternionDest=new Qe,this._lastTime=-1,window.isSecureContext===!1&&console.error("DeviceOrientationControls2: DeviceOrientationEvent is only available in secure contexts (https)"),this.object=e,this.lastOrder=this.object.rotation.order,this.object.rotation.reorder("YXZ"),this.connect()}resetView(){this._initQuaternionDest.__init=!1}connect(){this.enabled||(this.onScreenOrientationChangeEvent(),window.DeviceOrientationEvent!==void 0&&typeof window.DeviceOrientationEvent.requestPermission=="function"?window.DeviceOrientationEvent.requestPermission().then(e=>{e=="granted"&&(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent))}).catch(e=>{console.error("DeviceOrientationControls2: Unable to use DeviceOrientation API:",e)}):(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent)),this.enabled=!0,this._initQuaternion.copy(this.object.quaternion),this._initQuaternionInvert.copy(this.object.quaternion).invert())}disconnect(){this.enabled&&(window.removeEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.removeEventListener("deviceorientation",this.onDeviceOrientationChangeEvent),this._initQuaternion.identity(),this._initQuaternionInvert.identity(),this._initQuaternionDest=new Qe,this.object.rotation.reorder(this.lastOrder),this.lastOrder="XYZ",this.enabled=!1)}update(){if(!this.enabled)return;const e=this.deviceOrientation;if(e){const t=e.alpha!==null?Ut.degToRad(e.alpha):0,i=e.beta!==null?Ut.degToRad(e.beta):0,n=e.gamma!==null?Ut.degToRad(e.gamma):0,s=this.screenOrientation?Ut.degToRad(this.screenOrientation.angle):0;this.setObjectQuaternion(t,i,n,s),8*(1-this.lastQuaternion.dot(this.object.quaternion))>RF&&(this.lastQuaternion.copy(this.object.quaternion),this.dispatchEvent(DF))}}dispose(){this.disconnect()}setObjectQuaternion(e,t,i,n){const s=Mn()/1e3;GS.set(t,e,-i,"YXZ"),Xc.setFromEuler(GS),Xc.multiply(PF),Xc.multiply(IF.setFromAxisAngle(TF,-n)),this._initQuaternionDest.__init||(this._initQuaternionDest.copy(Xc).invert(),this._initQuaternionDest.__init=!0),Xc.premultiply(this._initQuaternionDest);const a=1/60;this.object.quaternion.multiply(this._initQuaternionInvert),this.object.quaternion.slerp(Xc,this.dampingFactor/(Math.min(1,s-this._lastTime)/a)),this.object.quaternion.multiply(this._initQuaternion),this._lastTime=s}},td([z(),Oe("Damping",[0,1],.01)],f.DeviceOrientationControls2.prototype,"dampingFactor",2),td([lt("Reset View")],f.DeviceOrientationControls2.prototype,"resetView",1),td([lt()],f.DeviceOrientationControls2.prototype,"connect",1),td([lt()],f.DeviceOrientationControls2.prototype,"disconnect",1),f.DeviceOrientationControls2=td([Aa("Device Orientation Controls")],f.DeviceOrientationControls2);const ya=new x,dl=new x,lm=new x,yv=new x,cm=new x,Yc=new x;let vv=1;const BF=new x(0,1,0);class LF extends ov{constructor(e,t){super(e,t),this.throttleUpdate=60,this.targetOffset=new x(0,0,0);const i=this.update;this.update=()=>this._update(i)}_update(e){this.target.add(this.targetOffset),ya.copy(this.object.position).sub(this.target),vv=ya.length(),Yc.copy(this.target);const t=e();return Yc.sub(this.target),ya.copy(this.object.position).sub(this.target),vv/=ya.length(),this.target.add(Yc),this.object.position.copy(this.target).add(ya),ya.normalize(),dl.crossVectors(BF,ya).normalize(),lm.crossVectors(ya,dl).normalize(),yv.crossVectors(dl,lm).normalize().negate(),dl.length()>.1&&this.object.up.crossVectors(ya.clone().normalize(),dl),this.enablePan&&(cm.set(0,0,0).addScaledVector(dl,Yc.x).addScaledVector(lm,Yc.y).addScaledVector(yv,Yc.z),this.targetOffset.add(cm),this.targetOffset.multiplyScalar(1/vv)),cm.set(0,0,0).addScaledVector(dl,-this.targetOffset.x).addScaledVector(lm,-this.targetOffset.y).addScaledVector(yv,-this.targetOffset.z),this.object.lookAt(cm.add(this.target)),this.object.updateMatrixWorld(),this.object.isCamera&&this.object.updateProjectionMatrix(),this.target.sub(this.targetOffset),t}}const Us=class Us extends en{constructor(){super(...arguments),this._vector=new x}expandByObject(e,t=!1,i=!1,n){if(e.userData?.bboxVisible===!1)return this;if(!e.visible&&i)return this;if(n&&n(e))return this;e.updateWorldMatrix(!1,!1);const s=e.geometry;if(s!==void 0){const o=s.getAttribute("position");if(t===!0&&o!==void 0&&Object.getPrototypeOf(s).computeBoundingBox===$e.prototype.computeBoundingBox)for(let l=0,c=o.count;l<c;l++)e.isMesh===!0?e.getVertexPosition(l,this._vector):this._vector.fromBufferAttribute(o,l),this._vector.applyMatrix4(e.matrixWorld),this.expandByPoint(this._vector);else e.boundingBox!==void 0?((t||e.boundingBox===null)&&typeof e.computeBoundingBox=="function"&&e.computeBoundingBox(),e.boundingBox!==null?(Us._box.copy(e.boundingBox),Us._box.applyMatrix4(e.matrixWorld),this.union(Us._box)):console.warn("Box3B - Unable to compute bounds for",e)):(s.boundingBox===null&&s.computeBoundingBox(),s.boundingBox?(Us._box.copy(s.boundingBox),Us._box.applyMatrix4(e.matrixWorld),this.union(Us._box)):console.warn("Box3B - Unable to compute bounds for",e,s))}else e.boundingBox!==void 0&&((t||e.boundingBox===null)&&typeof e.computeBoundingBox=="function"&&e.computeBoundingBox(),e.boundingBox!==null?(Us._box.copy(e.boundingBox),Us._box.applyMatrix4(e.matrixWorld),this.union(Us._box)):console.warn("Box3B - Unable to compute bounds for",e));const a=e.children;for(let o=0,l=a.length;o<l;o++)this.expandByObject(a[o],t,i);return this}expandByObjects(e,t=!1,i=!1){for(let n=0,s=e.length;n<s;n++)this.expandByObject(e[n],t,i);return this}getPoints(){return[new x(this.min.x,this.min.y,this.min.z),new x(this.min.x,this.min.y,this.max.z),new x(this.min.x,this.max.y,this.min.z),new x(this.min.x,this.max.y,this.max.z),new x(this.max.x,this.min.y,this.min.z),new x(this.max.x,this.min.y,this.max.z),new x(this.max.x,this.max.y,this.min.z),new x(this.max.x,this.max.y,this.max.z)]}getScreenSpaceBounds(e){const t=this.getPoints(),i=new ky;for(const n of t){const s=n.project(e);i.min.min(s),i.max.max(s)}return i}};Us._box=new Us;let In=Us;function _v(r,e){let t,i;if(Array.isArray(r))for(const s of r){const a=_v(s,e);t===void 0||i===void 0?(t=a.min.clone(),i=a.max.clone()):(t.min(a.min),i.max(a.max))}const n=r;if(n.geometry!==void 0){const s=n.geometry.vertices;if(s===void 0&&n.geometry.attributes!==void 0&&"position"in n.geometry.attributes){const a=new x,o=n.geometry.attributes.position;for(let l=0;l<o.count*o.itemSize;l+=o.itemSize){a.set(o.array[l],o.array[l+1],o.array[3]);const h=a.applyMatrix4(r.matrixWorld).project(e),u=new $(h.x,h.y);t===void 0||i===void 0?(t=u.clone(),i=u.clone()):(t.min(u),i.max(u))}}else for(const a of s){const l=a.clone().applyMatrix4(r.matrixWorld).project(e),c=new $(l.x,l.y);t===void 0||i===void 0?(t=c.clone(),i=c.clone()):(t.min(c),i.max(c))}}if(r.children!==void 0)for(const s of r.children){const a=_v(s,e);t===void 0||i===void 0?(t=a.min.clone(),i=a.max.clone()):(t.min(a.min),i.max(a.max))}return new ky(t,i)}function zS(r){if(di._orig&&di._storage){if(di._storage===r)return;Object.assign(di,di._orig),delete di._orig,delete di._storage}const e={...di};di._orig=e,di._storage=r,di.get=(t,i,n)=>i?t.startsWith("data:")||t.startsWith("blob")||t.startsWith("chrome-extension")?Promise.resolve(void 0):r?.match(t).then(async s=>{if(s)switch(i){case"arraybuffer":return s.arrayBuffer();case"blob":return s.blob();case"document":return s.text().then(a=>new DOMParser().parseFromString(a,n??"text/html"));case"json":return s.json();default:if(n===void 0)return s.text();{const o=/charset="?([^;"\s]*)"?/i.exec(n),l=o&&o[1]?o[1].toLowerCase():void 0,c=new TextDecoder(l);return s.arrayBuffer().then(h=>c.decode(h))}}}):e.get(t),di.add=async(t,i,n)=>{if(!n)return e.add(t,i);t.startsWith("data:")||t.startsWith("blob")||t.startsWith("chrome-extension")||t.startsWith("asset://")||(await r?.match(t)&&await r?.delete(t),await r?.put(t,new Response(i,{status:200})).catch(s=>{console.warn(s)}))},di.remove=(t,i)=>{if(!i)return e.remove(t);r?.delete(t)}}function OF(r){const e=new As(new Uint8Array([Math.floor(r.r*255),Math.floor(r.g*255),Math.floor(r.b*255),255]),1,1,Kt,Wt);return e.needsUpdate=!0,e.colorSpace=Dt,e}function UF(r){const e=new As(new Uint8Array([Math.floor(r.x*255),Math.floor(r.y*255),Math.floor(r.z*255),Math.floor(r.w*255)]),1,1,Kt,Wt);return e.needsUpdate=!0,e.colorSpace=Dt,e}function VS(r,e=3,t){let i,n,s,a,o;const l=r.byteLength/(e*2)|0;t=t||new Uint8ClampedArray(l*4);for(let c=0;c<l;c++){i=Hn.fromHalfFloat(r[c*e])*65504,n=Hn.fromHalfFloat(r[c*e+1])*65504,s=Hn.fromHalfFloat(r[c*e+2])*65504,a=Math.max(Math.max(i,n),s);const h=Math.ceil(Math.log2(a));o=Math.pow(2,h-8),t[c*4]=i/o|0,t[c*4+1]=n/o|0,t[c*4+2]=s/o|0,t[c*4+3]=h+128}return t}function va({uniforms:r,propKey:e,thisTarget:t=!1,onChange:i}={}){const n=!!r,s=!!e,a=t;return(o,l,c)=>{const h=d=>{const p=a?d:n?r:d.uniforms||d._uniforms||d.extraUniforms;let m=s?e:l;a&&(m="_"+m);let A=p[m];return A||(A={value:null},p[m]=A),A},u={get(){return h(this).value},set(d){const p=h(this);p.value!==d&&(p.value=d,an(this,"uniformsNeedUpdate",!0,!0),i&&zu.callFunction(i,this,[l,d]))}};if(c)return qn(c,"value")&&delete c.value,qn(c,"writable")&&delete c.writable,qn(c,"initializer")&&delete c.initializer,Object.assign(c,u);Object.defineProperty(o,l,u)}}function hm(r,e,t=!1,i,n,s){const a=!!e,o=!!r;return(l,c,h)=>{const u=p=>({t:a?e:p.defines||p._defines||p.extraDefines,p:o?r:c}),d={get(){const{t:p,p:m}=u(t?this:this.material);let A=p[m];return s&&(A=s(A)),A},set(p){const{t:m,p:A}=u(t?this:this.material);n&&(p=n(p)),an(m,A,p,!0),p===void 0&&delete m[A],i&&typeof i=="function"?zu.callFunction(i,this,[A,p]):an(t?this:this.material,"needsUpdate",!0,!0)}};if(h)return qn(h,"value")&&delete h.value,qn(h,"writable")&&delete h.writable,qn(h,"initializer")&&delete h.initializer,Object.assign(h,d);Object.defineProperty(l,c,d)}}function um(r,e,t=!1,i,n=!1){return hm(r,e,t,i,s=>s?"1":n?void 0:"0",s=>!!(s&&s!=="0"))}function Vt({obj:r,key:e,processVal:t,invProcessVal:i,onChange:n,onChangeParams:s=!0,allowUndefined:a=!1}){const o=!!e;return(l,c,h)=>{const u=p=>{let m=it(r)||p;typeof m=="string"&&(m=p[m]);let A=o&&it(e)||c,g;if(Array.isArray(A)){for(;A.length>1&&m&&typeof m=="object";)m=m[A[0]],A=A.slice(1);g=A.length?A[0]:c}else g=A;return{t:m,p:g}},d={get(){const{t:p,p:m}=u(this);if(!p||typeof p!="object")return;let A=p[m];return i&&(A=i(A)),A},set(p){const{t:m,p:A}=u(this);if(!m||typeof m!="object")return;t&&(p=t(p)),an(m,A,p,!0)&&p===void 0&&!a&&delete m[A];let y=n;y&&(typeof y=="string"||typeof y=="symbol")&&(y=this[y]),y&&typeof y=="function"&&zu.callFunction(y,this,s?[A,p]:[])}};if(h)return qn(h,"value")&&delete h.value,qn(h,"writable")&&delete h.writable,qn(h,"initializer")&&delete h.initializer,Object.assign(h,d);Object.defineProperty(l,c,d)}}function HS(r,e){let t;switch(e){case si:case Dt:t="";break;case vt:t="";break;case Gs:t="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",e),t="";break}return`#define ${r}( value ) ${t} ( value )`}function bv(r,e){return HS(r+"TexelToLinear",e??Dt)+`
`}function FF(r,e,t=!0){if(!e||!e.isReady)throw new Error("BufferGeometryUtils: Initialized MikkTSpace library required.");if(!r.hasAttribute("position")||!r.hasAttribute("normal")||!r.hasAttribute("uv"))throw new Error('BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.');function i(a){if(a.normalized||a.isInterleavedBufferAttribute){const o=new Float32Array(a.count*a.itemSize);for(let l=0,c=0;l<a.count;l++)o[c++]=a.getX(l),o[c++]=a.getY(l),a.itemSize>2&&(o[c++]=a.getZ(l));return o}return a.array instanceof Float32Array?a.array:new Float32Array(a.array)}const n=r.index?r.toNonIndexed():r,s=e.generateTangents(i(n.attributes.position),i(n.attributes.normal),i(n.attributes.uv));if(t)for(let a=3;a<s.length;a+=4)s[a]*=-1;return n.setAttribute("tangent",new Xe(s,4)),r!==n&&r.copy(n),r}function QS(r,e=!1){const t=r[0].index!==null,i=new Set(Object.keys(r[0].attributes)),n=new Set(Object.keys(r[0].morphAttributes)),s={},a={},o=r[0].morphTargetsRelative,l=new $e;let c=0;for(let h=0;h<r.length;++h){const u=r[h];let d=0;if(t!==(u.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in u.attributes){if(!i.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;s[p]===void 0&&(s[p]=[]),s[p].push(u.attributes[p]),d++}if(d!==i.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". Make sure all geometries have the same number of attributes."),null;if(o!==u.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in u.morphAttributes){if(!n.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+".  .morphAttributes must be consistent throughout all geometries."),null;a[p]===void 0&&(a[p]=[]),a[p].push(u.morphAttributes[p])}if(e){let p;if(t)p=u.index.count;else if(u.attributes.position!==void 0)p=u.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,p,h),c+=p}}if(t){let h=0;const u=[];for(let d=0;d<r.length;++d){const p=r[d].index;for(let m=0;m<p.count;++m)u.push(p.getX(m)+h);h+=r[d].attributes.position.count}l.setIndex(u)}for(const h in s){const u=dm(s[h]);if(!u)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" attribute."),null;l.setAttribute(h,u)}for(const h in a){const u=a[h][0].length;if(u===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[h]=[];for(let d=0;d<u;++d){const p=[];for(let A=0;A<a[h].length;++A)p.push(a[h][A][d]);const m=dm(p);if(!m)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" morphAttribute."),null;l.morphAttributes[h].push(m)}}return l}function dm(r){let e,t,i,n=-1,s=0;for(let c=0;c<r.length;++c){const h=r[c];if(e===void 0&&(e=h.array.constructor),e!==h.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=h.itemSize),t!==h.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(i===void 0&&(i=h.normalized),i!==h.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(n===-1&&(n=h.gpuType),n!==h.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=h.count*t}const a=new e(s),o=new Xe(a,t,i);let l=0;for(let c=0;c<r.length;++c){const h=r[c];if(h.isInterleavedBufferAttribute){const u=l/t;for(let d=0,p=h.count;d<p;d++)for(let m=0;m<t;m++){const A=h.getComponent(d,m);o.setComponent(d+u,m,A)}}else a.set(h.array,l);l+=h.count*t}return n!==void 0&&(o.gpuType=n),o}function NF(r){return r.isInstancedInterleavedBufferAttribute||r.isInterleavedBufferAttribute?fm(r):r.isInstancedBufferAttribute?new ha().copy(r):new Xe().copy(r)}function kF(r){let e,t=0,i=0;for(let c=0,h=r.length;c<h;++c){const u=r[c];if(e===void 0&&(e=u.array.constructor),e!==u.array.constructor)return console.error("AttributeBuffers of different types cannot be interleaved"),null;t+=u.array.length,i+=u.itemSize}const n=new Sc(new e(t),i);let s=0;const a=[],o=["getX","getY","getZ","getW"],l=["setX","setY","setZ","setW"];for(let c=0,h=r.length;c<h;c++){const u=r[c],d=u.itemSize,p=u.count,m=new On(n,d,s,u.normalized);a.push(m),s+=d;for(let A=0;A<p;A++)for(let g=0;g<d;g++)m[l[g]](A,u[o[g]](A))}return a}function fm(r){const e=r.data.array.constructor,t=r.count,i=r.itemSize,n=r.normalized,s=new e(t*i);let a;r.isInstancedInterleavedBufferAttribute?a=new ha(s,i,n,r.meshPerAttribute):a=new Xe(s,i,n);for(let o=0;o<t;o++)a.setX(o,r.getX(o)),i>=2&&a.setY(o,r.getY(o)),i>=3&&a.setZ(o,r.getZ(o)),i>=4&&a.setW(o,r.getW(o));return a}function GF(r){const e=r.attributes,t=r.morphTargets,i=new Map;for(const n in e){const s=e[n];s.isInterleavedBufferAttribute&&(i.has(s)||i.set(s,fm(s)),e[n]=i.get(s))}for(const n in t){const s=t[n];s.isInterleavedBufferAttribute&&(i.has(s)||i.set(s,fm(s)),t[n]=i.get(s))}}function zF(r){let e=0;for(const i in r.attributes){const n=r.getAttribute(i);e+=n.count*n.itemSize*n.array.BYTES_PER_ELEMENT}const t=r.getIndex();return e+=t?t.count*t.itemSize*t.array.BYTES_PER_ELEMENT:0,e}function jS(r,e=1e-4){const t=e>0;e=Math.max(e,Number.EPSILON);const i={},n=r.getIndex(),s=r.getAttribute("position"),a=n?n.count:s.count;let o=0;const l=Object.keys(r.attributes),c={},h={},u=[],d=["getX","getY","getZ","getW"],p=["setX","setY","setZ","setW"];for(let v=0,b=l.length;v<b;v++){const T=l[v],E=r.attributes[T];c[T]=new Xe(new E.array.constructor(E.count*E.itemSize),E.itemSize,E.normalized);const M=r.morphAttributes[T];M&&(h[T]=new Xe(new M.array.constructor(M.count*M.itemSize),M.itemSize,M.normalized))}const m=e*.5,A=Math.log10(1/e),g=Math.pow(10,A),y=m*g;for(let v=0;v<a;v++){const b=n?n.getX(v):v;let T="";for(let E=0,M=l.length;E<M&&t;E++){const S=l[E],w=r.getAttribute(S),C=w.itemSize;for(let D=0;D<C;D++)T+=`${~~(w[d[D]](b)*g+y)},`}if(t&&T in i)u.push(i[T]);else{for(let E=0,M=l.length;E<M;E++){const S=l[E],w=r.getAttribute(S),C=r.morphAttributes[S],D=w.itemSize,O=c[S],F=h[S];for(let G=0;G<D;G++){const j=d[G],W=p[G];if(O[W](o,w[j](b)),C)for(let K=0,q=C.length;K<q;K++)F[K][W](o,C[K][j](b))}}t&&(i[T]=o),u.push(o),o++}}const _=r.clone();for(const v in r.attributes){const b=c[v];if(_.setAttribute(v,new Xe(b.array.slice(0,o*b.itemSize),b.itemSize,b.normalized)),v in h)for(let T=0;T<h[v].length;T++){const E=h[v][T];_.morphAttributes[v][T]=new Xe(E.array.slice(0,o*E.itemSize),E.itemSize,E.normalized)}}return _.setIndex(u),_}function wv(r,e){if(e===RP)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),r;if(e===CA||e===hw){let t=r.getIndex();if(t===null){const a=[],o=r.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);r.setIndex(a),t=r.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),r}const i=t.count-2,n=[];if(e===CA)for(let a=1;a<=i;a++)n.push(t.getX(0)),n.push(t.getX(a)),n.push(t.getX(a+1));else for(let a=0;a<i;a++)a%2===0?(n.push(t.getX(a)),n.push(t.getX(a+1)),n.push(t.getX(a+2))):(n.push(t.getX(a+2)),n.push(t.getX(a+1)),n.push(t.getX(a)));n.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=r.clone();return s.setIndex(n),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),r}function VF(r){const e=new x,t=new x,i=new x,n=new x,s=new x,a=new x,o=new x,l=new x,c=new x;function h(oe,re,Ce,Ie,Ue,te,ce,me){e.fromBufferAttribute(re,Ue),t.fromBufferAttribute(re,te),i.fromBufferAttribute(re,ce);const we=oe.morphTargetInfluences;if(Ce&&we){o.set(0,0,0),l.set(0,0,0),c.set(0,0,0);for(let je=0,ht=Ce.length;je<ht;je++){const Ze=we[je],Y=Ce[je];Ze!==0&&(n.fromBufferAttribute(Y,Ue),s.fromBufferAttribute(Y,te),a.fromBufferAttribute(Y,ce),Ie?(o.addScaledVector(n,Ze),l.addScaledVector(s,Ze),c.addScaledVector(a,Ze)):(o.addScaledVector(n.sub(e),Ze),l.addScaledVector(s.sub(t),Ze),c.addScaledVector(a.sub(i),Ze)))}e.add(o),t.add(l),i.add(c)}oe.isSkinnedMesh&&(oe.applyBoneTransform(Ue,e),oe.applyBoneTransform(te,t),oe.applyBoneTransform(ce,i)),me[Ue*3+0]=e.x,me[Ue*3+1]=e.y,me[Ue*3+2]=e.z,me[te*3+0]=t.x,me[te*3+1]=t.y,me[te*3+2]=t.z,me[ce*3+0]=i.x,me[ce*3+1]=i.y,me[ce*3+2]=i.z}const u=r.geometry,d=r.material;let p,m,A;const g=u.index,y=u.attributes.position,_=u.morphAttributes.position,v=u.morphTargetsRelative,b=u.attributes.normal,T=u.morphAttributes.position,E=u.groups,M=u.drawRange;let S,w,C,D,O,F,G;const j=new Float32Array(y.count*y.itemSize),W=new Float32Array(b.count*b.itemSize);if(g!==null)if(Array.isArray(d))for(S=0,C=E.length;S<C;S++)for(O=E[S],F=Math.max(O.start,M.start),G=Math.min(O.start+O.count,M.start+M.count),w=F,D=G;w<D;w+=3)p=g.getX(w),m=g.getX(w+1),A=g.getX(w+2),h(r,y,_,v,p,m,A,j),h(r,b,T,v,p,m,A,W);else for(F=Math.max(0,M.start),G=Math.min(g.count,M.start+M.count),S=F,C=G;S<C;S+=3)p=g.getX(S),m=g.getX(S+1),A=g.getX(S+2),h(r,y,_,v,p,m,A,j),h(r,b,T,v,p,m,A,W);else if(Array.isArray(d))for(S=0,C=E.length;S<C;S++)for(O=E[S],F=Math.max(O.start,M.start),G=Math.min(O.start+O.count,M.start+M.count),w=F,D=G;w<D;w+=3)p=w,m=w+1,A=w+2,h(r,y,_,v,p,m,A,j),h(r,b,T,v,p,m,A,W);else for(F=Math.max(0,M.start),G=Math.min(y.count,M.start+M.count),S=F,C=G;S<C;S+=3)p=S,m=S+1,A=S+2,h(r,y,_,v,p,m,A,j),h(r,b,T,v,p,m,A,W);const K=new Me(j,3),q=new Me(W,3);return{positionAttribute:y,normalAttribute:b,morphedPositionAttribute:K,morphedNormalAttribute:q}}function HF(r){if(r.groups.length===0)return console.warn("THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge."),r;let e=r.groups;if(e=e.sort((a,o)=>a.materialIndex!==o.materialIndex?a.materialIndex-o.materialIndex:a.start-o.start),r.getIndex()===null){const a=r.getAttribute("position"),o=[];for(let l=0;l<a.count;l+=3)o.push(l,l+1,l+2);r.setIndex(o)}const t=r.getIndex(),i=[];for(let a=0;a<e.length;a++){const o=e[a],l=o.start,c=l+o.count;for(let h=l;h<c;h++)i.push(t.getX(h))}r.dispose(),r.setIndex(i);let n=0;for(let a=0;a<e.length;a++){const o=e[a];o.start=n,n+=o.count}let s=e[0];r.groups=[s];for(let a=1;a<e.length;a++){const o=e[a];s.materialIndex===o.materialIndex?s.count+=o.count:(s=o,r.groups.push(s))}return r}function QF(r,e=Math.PI/3){const t=Math.cos(e),i=(1+1e-10)*100,n=[new x,new x,new x],s=new x,a=new x,o=new x,l=new x;function c(A){const g=~~(A.x*i),y=~~(A.y*i),_=~~(A.z*i);return`${g},${y},${_}`}const h=r.index?r.toNonIndexed():r,u=h.attributes.position,d={};for(let A=0,g=u.count/3;A<g;A++){const y=3*A,_=n[0].fromBufferAttribute(u,y+0),v=n[1].fromBufferAttribute(u,y+1),b=n[2].fromBufferAttribute(u,y+2);s.subVectors(b,v),a.subVectors(_,v);const T=new x().crossVectors(s,a).normalize();for(let E=0;E<3;E++){const M=n[E],S=c(M);S in d||(d[S]=[]),d[S].push(T)}}const p=new Float32Array(u.count*3),m=new Xe(p,3,!1);for(let A=0,g=u.count/3;A<g;A++){const y=3*A,_=n[0].fromBufferAttribute(u,y+0),v=n[1].fromBufferAttribute(u,y+1),b=n[2].fromBufferAttribute(u,y+2);s.subVectors(b,v),a.subVectors(_,v),o.crossVectors(s,a).normalize();for(let T=0;T<3;T++){const E=n[T],M=c(E),S=d[M];l.set(0,0,0);for(let w=0,C=S.length;w<C;w++){const D=S[w];o.dot(D)>t&&l.add(D)}l.normalize(),m.setXYZ(y+T,l.x,l.y,l.z)}}return h.setAttribute("normal",m),h}function jF(r,e=!1){return console.warn("THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries()."),QS(r,e)}function WF(r){return console.warn("THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes()."),dm(r)}function Cv(r,e=-1){return jS(r,e)}function Ui(){return Ut.generateUUID()}function xv(...r){if(r.length>1)return r.some(i=>xv(i));const e=r[0];if(e.isTexture)return Array.from(e.appliedObjects||[]).some(i=>xv(i))??!1;const t=e.isObject3D?[e]:e.appliedMeshes;for(const i of t){let n=!1;if(i.traverseAncestors(s=>s.isScene&&(n=!0)),n)return!0}return!1}function WS(r,e,t=new Qe){return e.premultiply(r.getWorldQuaternion(t).invert())}function qF(r,e,t=new Qe){return e.premultiply(r.getWorldQuaternion(t))}function id(r,e,t,i=!1){const n=i?Gu(r,e,!1):r in e?e[r]:void 0;n&&n.isTexture&&t.set(r,n)}function Sv(r){if(!r)return Wt;const e=r.extensions.has("EXT_color_buffer_half_float")||r.capabilities.isWebGL2&&r.extensions.has("EXT_color_buffer_float"),t=r.capabilities.isWebGL2||r.extensions.has("OES_texture_float")||r.extensions.has("WEBGL_color_buffer_float");return e?$t:t?zt:Wt}function Ev(r,e,t){const i=t?.data??new Uint8ClampedArray(r.height*r.width*4),n=r.data instanceof Float32Array,s=r.data instanceof Uint16Array;for(let a=0;a<i.length;a++)n?i[a]=r.data[a]*255:s?i[a]=Hn.fromHalfFloat(r.data[a])*255:i[a]=r.data[a],e===Dt&&(i[a]=qx(i[a]/255)*255);return t??new ImageData(i,r.width,r.height)}function pm(r,e,t=!1){let i;return r.isDataTexture?i=Ev(r.image,r.colorSpace):i=r.image,qS(i,e,t)}function qS(r,e,t=!1){let i,n;window.VideoFrame||(window.VideoFrame=HTMLVideoElement),r instanceof window.VideoFrame?(i=r.displayWidth,n=r.displayHeight):(i=r.width||r.videoWidth||r.naturalWidth||1,n=r.height||r.videoHeight||r.naturalHeight||1),window.VideoFrame===HTMLVideoElement&&delete window.VideoFrame;const s=document.createElement("canvas");s.width=Math.min(e,i),s.height=Math.floor(1+s.width*n/i);const a=s.getContext("2d");if(!a)return console.error("textureToDataUrl: could not get canvas context"),s;t===!0&&(a.translate(0,s.height),a.scale(1,-1));let o=!1;if(r.data!==void 0){const l=r;if(i!==s.width||n!==s.height){const c=document.createElement("canvas");c.width=i,c.height=n;const h=c.getContext("2d");h?(h.putImageData(l,0,0),a.drawImage(c,0,0,s.width,s.height)):(console.error("textureToDataUrl: could not get temp canvas context"),a.putImageData(l,0,0))}else a.putImageData(l,0,0),t&&(o=!0)}else a.drawImage(r,0,0,s.width,s.height);return o?Yy(s):s}function XF(r,e,t,i,n){return pm(r,e,t).toDataURL(i,n)}async function YF(r,e,t,i,n){const s=pm(r,e,t);return new Promise((a,o)=>{s.toBlob(l=>{l?a(l):o(new Error("Failed to create blob"))},i,n)})}const $F={None:gn,Normal:xr,Additive:rf,Subtractive:af,Multiply:of,Custom:ir},KF={UV:Kh,Cube:Kr,CubeUV:Yl,Equirectangular:Jr},JF={None:"",SRGB:vt,LinearSRGB:Dt,RGBM16:Gs,DisplayP3:eu},ZF={UnsignedByte:Wt,Byte:kb,Short:Gb,UnsignedShort:oA,Int:lA,UnsignedInt:ea,Float:zt,HalfFloat:$t,UnsignedShort4444:cA,UnsignedShort5551:hA,UnsignedInt248:$l},e3={Basic:xA,RGBADepthPacking:tc};function nd(r){return{map:r,inv:Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),uiConfig:Object.entries(r).map(([e,t])=>({label:e,value:t}))}}const Mv={Blending:nd($F),AnyMapping:nd(KF),ColorSpace:nd(JF),TextureDataType:nd(ZF),DepthPackingStrategies:nd(e3)},mm=new ImageData(new Uint8ClampedArray([255,255,255,255]),1,1),gm=new Rt(mm);var t3=Object.defineProperty,Tv=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&t3(e,t,n),n};const Am=(La=class extends wi{constructor(e,t,i,n){super(),this.hoverEnabled=!1,this.multiSelectEnabled=!0,this.selectionMode="object",this.pickingMode="auto",this.extraObjects=[],this._mouseDownPos=new $,this._onSelectedRemoved=s=>{const a=s.target;if(this._selected.includes(a)){const o=this._selected.filter(l=>l!==a);this.setSelected(o.length?o.length===1?o[0]:o:null,!1)}},this._onPointerMove=s=>{if(s.isPrimary!==!1&&(this.updateMouseFromEvent(s),this.hoverEnabled)){const{obj:a,intersects:o}=this._hitObject();this.setHoverObject(a,!0,o||void 0)}},this._onPointerLeave=s=>{s.isPrimary!==!1&&(this.domElement.style.cursor=this.cursorStyles.default,(this.hoverEnabled||this.hoverObject)&&this.setHoverObject(null))},this._onPointerEnter=s=>{},this._onPointerCancel=s=>{},this._onPointerDown=s=>{s.isPrimary!==!1&&(this.domElement.style.cursor=this.cursorStyles.down,this._mouseDownTime=this.time,this._mouseDownPos.copy(this.mouse))},this._onPointerUp=s=>{if(s.isPrimary===!1)return;this.domElement.style.cursor=this.cursorStyles.default,this._mouseUpTime=this.time;const a=this.mouseDownDeltaTime,o=this._mouseDownPos.distanceTo(this.mouse);a<La.PointerClickMaxTime&&o<La.PointerClickMaxDistance&&this._onPointerClick(s)},this._onPointerClick=s=>{if(s.isPrimary===!1)return;this.updateMouseFromEvent(s);const{obj:a,intersects:o}=this._hitObject();if(!o?.consumed)if(this.multiSelectEnabled&&(s.shiftKey||s.ctrlKey||s.metaKey)&&a&&this.selectionMode==="object"){const l=[...this._selected],c=l.indexOf(a);c>=0?l.splice(c,1):l.unshift(a),this.setSelected(l.length?l.length===1?l[0]:l:null,!0)}else this.setSelected(a,!0,o||void 0)},this._root=e,this._camera=i,this.domElement=t,this._time=this.time,this._mouseDownTime=0,this._mouseUpTime=1,this.selectionCondition=n??(s=>s.userData.userSelectable!==!1&&s.userData.bboxVisible!==!1&&s.material!=null&&s.material.type!=="ShadowMaterial"),this.raycaster=new Uu,this.raycaster.params.Line2={threshold:.01},this.mouse=new $,this._selected=[],this._hovering=[],this.cursorStyles={default:"grab",down:"grabbing"},this.domElement.style.touchAction="none",this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerleave",this._onPointerLeave),this.domElement.addEventListener("pointerout",this._onPointerLeave),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("pointerenter",this._onPointerEnter),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp)}dispose(){this.setSelected(null),this.setHoverObject(null),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerleave",this._onPointerLeave),this.domElement.removeEventListener("pointerout",this._onPointerLeave),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("pointerenter",this._onPointerEnter),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp)}get camera(){return this._camera}set camera(e){this._camera=e}get selectedObject(){return this._selected.length>0?this._selected[0]:null}get selectedObjects(){return[...this._selected]}setSelected(e,t=!0,i){e&&(e?.isObject3D&&this.selectionMode!=="object"?this.selectionMode="object":e?.isMaterial&&this.selectionMode!=="material"?this.selectionMode="material":e?.isTexture&&this.selectionMode!=="texture"?this.selectionMode="texture":e?.isBufferGeometry&&this.selectionMode!=="geometry"&&(this.selectionMode="geometry"));const n=this._selectedIntersects;if(Array.isArray(e)){if(this._selected.length===e.length&&this._selected.every((o,l)=>o===e[l]))return}else if(!this._selected.length&&!e||this._selected.length===1&&this._selected[0]===e&&n?.selectedObject===i?.selectedObject&&n?.selectedWidget===i?.selectedWidget&&n?.selectedHandle===i?.selectedHandle)return;const s=[...this._selected];this._selected=e?Array.isArray(e)?[...e]:[e]:[],this._selectedIntersects=i||void 0;for(const o of s)o&&o.removeEventListener&&o.removeEventListener("__unregister",this._onSelectedRemoved);for(const o of this._selected)o&&o.addEventListener&&o.addEventListener("__unregister",this._onSelectedRemoved);const a=this.selectedObject;this.dispatchEvent({type:"selectedObjectChanged",object:a?.isObject3D?a:null,objects:[...this._selected],material:a?.isMaterial?a:null,value:a,lastValue:s.length?s[0]:null,lastValues:[...s],intersects:i}),t&&this.undoManager?.record({undo:()=>this.setSelected(s.length?s.length===1?s[0]:s:null,!1,n),redo:()=>this.setSelected(e,!1,i)})}get hoverObject(){return this._hovering.length>0?this._hovering[0]:null}setHoverObject(e,t=!0,i){if(!this._hovering.length&&!e||this._hovering.length===1&&this._hovering[0]===e&&this._hoveringIntersects?.selectedObject===i?.selectedObject&&this._hoveringIntersects?.selectedWidget===i?.selectedWidget&&this._hoveringIntersects?.selectedHandle===i?.selectedHandle)return;this._hovering=e?Array.isArray(e)?[...e]:[e]:[],this._hoveringIntersects=i||void 0;const n=this.hoverObject;this.dispatchEvent({type:"hoverObjectChanged",object:n?.isObject3D?n:null,material:n?.isMaterial?n:null,value:n,intersects:i})}get time(){return this._time=Mn(),this._time}get isMouseDown(){return this.mouseDownDeltaTime<0}get mouseDownDeltaTime(){return this._mouseUpTime-this._mouseDownTime}updateMouseFromEvent(e){const t=this.domElement.getBoundingClientRect();this.mouse.x=(e.clientX-t.x)/t.width*2-1,this.mouse.y=-((e.clientY-t.y)/t.height)*2+1}_hitObject(){const e=this.checkIntersection();e?this.dispatchEvent({type:"hitObject",time:this.time,intersects:e}):this.dispatchEvent({type:"hitObject",time:this.time,intersects:{selectedObject:null,intersect:null,intersects:[],mouse:this.mouse.clone()}});let t=e?.selectedObject||null;if(t)switch(this.pickingMode==="auto"?this.selectionMode:this.pickingMode){case"material":t.material&&(t=Array.isArray(t.material)?t.material[0]:t.material);break;case"texture":if(t.material){const n=Array.isArray(t.material)?t.material[0]:t.material;t=n.map||n.normalMap||n.roughnessMap||n.metalnessMap||n.aoMap||null}else t=null;break;case"geometry":t=t.geometry||null;break}return{obj:t,intersects:e}}checkIntersection(){const e=this._camera;if(!e)return null;this.raycaster.setFromCamera(this.mouse,e);let t=this.raycaster.intersectObjects([this._root,...this.extraObjects],!0);const i=[];t=t.filter(l=>i.includes(l.object.id)?!1:(i.push(l.object.id),!0));let s=null,a;const o=[];for(const l of t){for(s=l.object,a=l;s!=null&&(!s.visible||!this.selectionCondition(s));)s=s.parent;s!=null&&(l.object=s,o.push(l))}if(t=o,t.length>0){if(s=t[0].object,a=t[0],this._firstHit&&s.id!==this._firstHit.id)s=a.object;else for(let l=0;l<t.length;l++)if(this.selectedObject&&this.selectedObject.id===t[l].object.id){const c=l+1;if(c<t.length)a=t[c],s=a.object;else return null}this._firstHit=t[0].object}return s&&a&&s?{selectedObject:s,intersect:a,intersects:t,mouse:this.mouse.clone()}:null}isHovering(){return this.hoverObject!=null}isSelected(){return this.selectedObject!=null}},La.PointerClickMaxTime=200,La.PointerClickMaxDistance=.1,La);Tv([so("multiSelectChanged")],Am.prototype,"multiSelectEnabled"),Tv([so("selectionModeChanged")],Am.prototype,"selectionMode"),Tv([so("pickingModeChanged")],Am.prototype,"pickingMode");let XS=Am;function Iv(r){if(!r.isMaterial&&!r.isBufferGeometry)return;const e=Array.from(r.appliedMeshes).filter(s=>!s.isInstancedMesh&&!!s.parent&&s.children.length===0&&!Array.isArray(s.material));if(e.length<2)return;const t=s=>s.parent.uuid+"_"+s.geometry?.uuid+"_"+s.material?.uuid,i=new Map;for(const s of e){const a=t(s);i.has(a)||i.set(a,[]),i.get(a).push(s),s.updateMatrix()}const n=i.keys();for(const s of n){const a=i.get(s),o=a[0];if(!o||a.length<2)continue;const l=new Bc(o.geometry,o.material,a.length),c=o.userData;o.userData={},l.copy(o),Sm(l.userData,c);const h=o.parent;l.position.set(0,0,0),l.rotation.set(0,0,0),l.scale.set(1,1,1),l.updateMatrix();const u=new Float32Array(l.count*3),d=new Float32Array(l.count*4),p=new Float32Array(l.count*3);for(let m=0;m<a.length;m++){const A=a[m],g=A.matrix;g.determinant()<0&&(g.elements[0]*=-1,g.elements[1]*=-1,g.elements[2]*=-1),l.setMatrixAt(m,g),A.position.toArray(u,m*3),A.quaternion.toArray(d,m*4),A.scale.toArray(p,m*3),A.removeFromParent(),A.material=void 0,A.geometry=void 0}l.sourceTrs={TRANSLATION:new Xe(u,3),ROTATION:new Xe(d,4),SCALE:new Xe(p,3)},l.instanceMatrix.needsUpdate=!0,h.add(l),h.setDirty()}}const YS={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform sampler2D tDiffuse;
		uniform float h;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;

			gl_FragColor = sum;

		}`},$S={name:"VerticalBlurShader",uniforms:{tDiffuse:{value:null},v:{value:1/512}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform sampler2D tDiffuse;
		uniform float v;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;

			gl_FragColor = sum;

		}`};class KS{constructor(e){this._viewer=e,this.horizontalBlurMaterial=new nn(YS),this.verticalBlurMaterial=new nn($S),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial.depthTest=!1}blur(e,t,i,n=1){this.horizontalBlurMaterial.uniforms.h.value=n,this.verticalBlurMaterial.uniforms.v.value=n,this._viewer.renderManager.blit(i,{material:this.horizontalBlurMaterial,clear:!0,source:e}),this._viewer.renderManager.blit(t,{material:this.verticalBlurMaterial,clear:!0,source:i.texture})}dispose(){this.horizontalBlurMaterial.dispose(),this.verticalBlurMaterial.dispose()}}function Pv(r,e,t,i=7,n=new x(0,0,1.5),s=new Vi(45,1,.1,1e3)){const a=e.visible;e.visible=!0;const o=new In().expandByObject(e,!0,!0),l=o.getCenter(new x),c=o.getSize(new x);s.position.copy(l).add(n.clone().multiplyScalar(Math.max(c.x,c.y,c.z))),s.lookAt(l),e&&e.traverseVisible(u=>{u.layers.enable(i)}),i>0?s.layers.set(i):s.layers.enableAll(),r.setRenderTarget(null),r.clear(),typeof r.renderWithModes=="function"?r.renderWithModes({backgroundRender:!1},()=>{r.render(t??e,s)}):r.render(t??e,s);const h=r.domElement.toDataURL("image/png");return r.clear(),e.visible=a,e.traverseVisible(u=>{u.layers.disable(i)}),s.layers.enableAll(),h}class JS{constructor(){this._lights=[],this.shapes={sphere:new ye(new Ds(1)),cube:new ye(new mi(1,1,1)),cylinder:new ye(new sn(.5,.5,1))};const e=new qa;this._channel=7;const t=new Dp(16777215,4473924,1);t.position.set(0,10,0),t.layers.set(this._channel),e.add(t),this._lights.push(t),this._scene=e}dispose(){[...this._lights].forEach(e=>e.dispose()),Object.values(this.shapes).forEach(e=>{e.geometry&&e.geometry.dispose()})}generate(e,t,i,n="sphere"){const s=this.shapes[n]||new ye(new Ds(1));s.material=e,s.geometry.attributes.tangent||s.geometry.computeTangents(),this._scene.add(s),this._scene.environment=i??null;const a=e.envMapIntensity;typeof a=="number"&&(e.envMapIntensity=Math.max(a,2));const o=Pv(t,s,this._scene,this._channel,new x(0,0,1.5));return typeof a=="number"&&(e.envMapIntensity=a),this._scene.remove(s),s.material=void 0,o}}const ZS=new en,ym=new x;class Hs extends By{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry";const e=[-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],t=[-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],i=[0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5];this.setIndex(i),this.setAttribute("position",new Me(e,3)),this.setAttribute("uv",new Me(t,2))}applyMatrix4(e){const t=this.attributes.instanceStart,i=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),i.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const i=new Ou(t,6,1);return this.setAttribute("instanceStart",new On(i,3,0)),this.setAttribute("instanceEnd",new On(i,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const i=new Ou(t,6,1);return this.setAttribute("instanceColorStart",new On(i,3,0)),this.setAttribute("instanceColorEnd",new On(i,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new Ip(e.geometry)),this}fromLineSegments(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new en);const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),ZS.setFromBufferAttribute(t),this.boundingBox.union(ZS))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){const i=this.boundingSphere.center;this.boundingBox.getCenter(i);let n=0;for(let s=0,a=e.count;s<a;s++)ym.fromBufferAttribute(e,s),n=Math.max(n,i.distanceToSquared(ym)),ym.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(ym));this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",this)}}toJSON(){}applyMatrix(e){return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."),this.applyMatrix4(e)}}Re.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new $(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Di.line={uniforms:ko.merge([Re.common,Re.fog,Re.line]),vertexShader:`
		#include <common>
		#include <color_pars_vertex>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>
		#include <clipping_planes_pars_vertex>

		uniform float linewidth;
		uniform vec2 resolution;

		attribute vec3 instanceStart;
		attribute vec3 instanceEnd;

		attribute vec3 instanceColorStart;
		attribute vec3 instanceColorEnd;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#ifdef USE_DASH

			uniform float dashScale;
			attribute float instanceDistanceStart;
			attribute float instanceDistanceEnd;
			varying float vLineDistance;

		#endif

		void trimSegment( const in vec4 start, inout vec4 end ) {

			// trim end segment so it terminates between the camera plane and the near plane

			// conservative estimate of the near plane
			float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
			float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
			float nearEstimate = - 0.5 * b / a;

			float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

			end.xyz = mix( start.xyz, end.xyz, alpha );

		}

		void main() {

			#ifdef USE_COLOR

				vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

			#endif

			#ifdef USE_DASH

				vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
				vUv = uv;

			#endif

			float aspect = resolution.x / resolution.y;

			// camera space
			vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
			vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

			#ifdef WORLD_UNITS

				worldStart = start.xyz;
				worldEnd = end.xyz;

			#else

				vUv = uv;

			#endif

			// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
			// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
			// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
			// perhaps there is a more elegant solution -- WestLangley

			bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

			if ( perspective ) {

				if ( start.z < 0.0 && end.z >= 0.0 ) {

					trimSegment( start, end );

				} else if ( end.z < 0.0 && start.z >= 0.0 ) {

					trimSegment( end, start );

				}

			}

			// clip space
			vec4 clipStart = projectionMatrix * start;
			vec4 clipEnd = projectionMatrix * end;

			// ndc space
			vec3 ndcStart = clipStart.xyz / clipStart.w;
			vec3 ndcEnd = clipEnd.xyz / clipEnd.w;

			// direction
			vec2 dir = ndcEnd.xy - ndcStart.xy;

			// account for clip-space aspect ratio
			dir.x *= aspect;
			dir = normalize( dir );

			#ifdef WORLD_UNITS

				vec3 worldDir = normalize( end.xyz - start.xyz );
				vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
				vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
				vec3 worldFwd = cross( worldDir, worldUp );
				worldPos = position.y < 0.5 ? start: end;

				// height offset
				float hw = linewidth * 0.5;
				worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;

				// don't extend the line if we're rendering dashes because we
				// won't be rendering the endcaps
				#ifndef USE_DASH

					// cap extension
					worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;

					// add width to the box
					worldPos.xyz += worldFwd * hw;

					// endcaps
					if ( position.y > 1.0 || position.y < 0.0 ) {

						worldPos.xyz -= worldFwd * 2.0 * hw;

					}

				#endif

				// project the worldpos
				vec4 clip = projectionMatrix * worldPos;

				// shift the depth of the projected points so the line
				// segments overlap neatly
				vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
				clip.z = clipPose.z * clip.w;

			#else

				vec2 offset = vec2( dir.y, - dir.x );
				// undo aspect ratio adjustment
				dir.x /= aspect;
				offset.x /= aspect;

				// sign flip
				if ( position.x < 0.0 ) offset *= - 1.0;

				// endcaps
				if ( position.y < 0.0 ) {

					offset += - dir;

				} else if ( position.y > 1.0 ) {

					offset += dir;

				}

				// adjust for linewidth
				offset *= linewidth;

				// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
				offset /= resolution.y;

				// select end
				vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

				// back to clip space
				offset *= clip.w;

				clip.xy += offset;

			#endif

			gl_Position = clip;

			vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation

			#include <logdepthbuf_vertex>
			#include <clipping_planes_vertex>
			#include <fog_vertex>

		}
		`,fragmentShader:`
		uniform vec3 diffuse;
		uniform float opacity;
		uniform float linewidth;

		#ifdef USE_DASH

			uniform float dashOffset;
			uniform float dashSize;
			uniform float gapSize;

		#endif

		varying float vLineDistance;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#include <common>
		#include <color_pars_fragment>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {

			float mua;
			float mub;

			vec3 p13 = p1 - p3;
			vec3 p43 = p4 - p3;

			vec3 p21 = p2 - p1;

			float d1343 = dot( p13, p43 );
			float d4321 = dot( p43, p21 );
			float d1321 = dot( p13, p21 );
			float d4343 = dot( p43, p43 );
			float d2121 = dot( p21, p21 );

			float denom = d2121 * d4343 - d4321 * d4321;

			float numer = d1343 * d4321 - d1321 * d4343;

			mua = numer / denom;
			mua = clamp( mua, 0.0, 1.0 );
			mub = ( d1343 + d4321 * ( mua ) ) / d4343;
			mub = clamp( mub, 0.0, 1.0 );

			return vec2( mua, mub );

		}

		void main() {

			#include <clipping_planes_fragment>

			#ifdef USE_DASH

				if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

				if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

			#endif

			float alpha = opacity;

			#ifdef WORLD_UNITS

				// Find the closest points on the view ray and the line segment
				vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
				vec3 lineDir = worldEnd - worldStart;
				vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );

				vec3 p1 = worldStart + lineDir * params.x;
				vec3 p2 = rayEnd * params.y;
				vec3 delta = p1 - p2;
				float len = length( delta );
				float norm = len / linewidth;

				#ifndef USE_DASH

					#ifdef USE_ALPHA_TO_COVERAGE

						float dnorm = fwidth( norm );
						alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );

					#else

						if ( norm > 0.5 ) {

							discard;

						}

					#endif

				#endif

			#else

				#ifdef USE_ALPHA_TO_COVERAGE

					// artifacts appear on some hardware if a derivative is taken within a conditional
					float a = vUv.x;
					float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
					float len2 = a * a + b * b;
					float dlen = fwidth( len2 );

					if ( abs( vUv.y ) > 1.0 ) {

						alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );

					}

				#else

					if ( abs( vUv.y ) > 1.0 ) {

						float a = vUv.x;
						float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
						float len2 = a * a + b * b;

						if ( len2 > 1.0 ) discard;

					}

				#endif

			#endif

			vec4 diffuseColor = vec4( diffuse, alpha );

			#include <logdepthbuf_fragment>
			#include <color_fragment>

			gl_FragColor = vec4( diffuseColor.rgb, alpha );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>
			#include <fog_fragment>
			#include <premultiplied_alpha_fragment>

		}
		`};class $c extends nn{constructor(e){super({type:"LineMaterial",uniforms:ko.clone(Di.line.uniforms),vertexShader:Di.line.vertexShader,fragmentShader:Di.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const eE=new x,tE=new x,Un=new rt,Fn=new rt,Lr=new rt,Dv=new x,Rv=new pe,Nn=new Gy,iE=new x,vm=new en,_m=new un,Or=new rt;let Ur,fl;function nE(r,e,t){return Or.set(0,0,-e,1).applyMatrix4(r.projectionMatrix),Or.multiplyScalar(1/Or.w),Or.x=fl/t.width,Or.y=fl/t.height,Or.applyMatrix4(r.projectionMatrixInverse),Or.multiplyScalar(1/Or.w),Math.abs(Math.max(Or.x,Or.y))}function i3(r,e){const t=r.matrixWorld,i=r.geometry,n=i.attributes.instanceStart,s=i.attributes.instanceEnd,a=Math.min(i.instanceCount,n.count);for(let o=0,l=a;o<l;o++){Nn.start.fromBufferAttribute(n,o),Nn.end.fromBufferAttribute(s,o),Nn.applyMatrix4(t);const c=new x,h=new x;Ur.distanceSqToSegment(Nn.start,Nn.end,h,c),h.distanceTo(c)<fl*.5&&e.push({point:h,pointOnLine:c,distance:Ur.origin.distanceTo(h),object:r,face:null,faceIndex:o,uv:null,uv1:null})}}function n3(r,e,t){const i=e.projectionMatrix,s=r.material.resolution,a=r.matrixWorld,o=r.geometry,l=o.attributes.instanceStart,c=o.attributes.instanceEnd,h=Math.min(o.instanceCount,l.count),u=-e.near;Ur.at(1,Lr),Lr.w=1,Lr.applyMatrix4(e.matrixWorldInverse),Lr.applyMatrix4(i),Lr.multiplyScalar(1/Lr.w),Lr.x*=s.x/2,Lr.y*=s.y/2,Lr.z=0,Dv.copy(Lr),Rv.multiplyMatrices(e.matrixWorldInverse,a);for(let d=0,p=h;d<p;d++){if(Un.fromBufferAttribute(l,d),Fn.fromBufferAttribute(c,d),Un.w=1,Fn.w=1,Un.applyMatrix4(Rv),Fn.applyMatrix4(Rv),Un.z>u&&Fn.z>u)continue;if(Un.z>u){const v=Un.z-Fn.z,b=(Un.z-u)/v;Un.lerp(Fn,b)}else if(Fn.z>u){const v=Fn.z-Un.z,b=(Fn.z-u)/v;Fn.lerp(Un,b)}Un.applyMatrix4(i),Fn.applyMatrix4(i),Un.multiplyScalar(1/Un.w),Fn.multiplyScalar(1/Fn.w),Un.x*=s.x/2,Un.y*=s.y/2,Fn.x*=s.x/2,Fn.y*=s.y/2,Nn.start.copy(Un),Nn.start.z=0,Nn.end.copy(Fn),Nn.end.z=0;const A=Nn.closestPointToPointParameter(Dv,!0);Nn.at(A,iE);const g=Ut.lerp(Un.z,Fn.z,A),y=g>=-1&&g<=1,_=Dv.distanceTo(iE)<fl*.5;if(y&&_){Nn.start.fromBufferAttribute(l,d),Nn.end.fromBufferAttribute(c,d),Nn.start.applyMatrix4(a),Nn.end.applyMatrix4(a);const v=new x,b=new x;Ur.distanceSqToSegment(Nn.start,Nn.end,b,v),t.push({point:b,pointOnLine:v,distance:Ur.origin.distanceTo(b),object:r,face:null,faceIndex:d,uv:null,uv1:null})}}}class _a extends ye{constructor(e=new Hs,t=new $c({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,i=e.attributes.instanceEnd,n=new Float32Array(2*t.count);for(let a=0,o=0,l=t.count;a<l;a++,o+=2)eE.fromBufferAttribute(t,a),tE.fromBufferAttribute(i,a),n[o]=o===0?0:n[o-1],n[o+1]=n[o]+eE.distanceTo(tE);const s=new Ou(n,2,1);return e.setAttribute("instanceDistanceStart",new On(s,1,0)),e.setAttribute("instanceDistanceEnd",new On(s,1,1)),this}raycast(e,t){const i=this.material.worldUnits,n=e.camera;n===null&&!i&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const s=e.params.Line2!==void 0&&e.params.Line2.threshold||0;Ur=e.ray;const a=this.matrixWorld,o=this.geometry,l=this.material;fl=l.linewidth+s,o.boundingSphere===null&&o.computeBoundingSphere(),_m.copy(o.boundingSphere).applyMatrix4(a);let c;if(i)c=fl*.5;else{const u=Math.max(n.near,_m.distanceToPoint(Ur.origin));c=nE(n,u,l.resolution)}if(_m.radius+=c,Ur.intersectsSphere(_m)===!1)return;o.boundingBox===null&&o.computeBoundingBox(),vm.copy(o.boundingBox).applyMatrix4(a);let h;if(i)h=fl*.5;else{const u=Math.max(n.near,vm.distanceToPoint(Ur.origin));h=nE(n,u,l.resolution)}vm.expandByScalar(h),Ur.intersectsBox(vm)!==!1&&(i?i3(this,t):n3(this,n,t))}}var s3=Object.defineProperty,r3=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&s3(e,t,n),n};const[sE,rE,aE,oE,lE,cE]=Array(6).fill(0).map((r,e)=>e),bm=[new se(16725587),new se(9100032),new se(2920447)],a3=new Lu,co=new x,pl=new Qe,wm=new Qe,Bv=new Qe,sd=new x,o3=2*Math.PI,hE=new Uu,Lv=new $,rd=new ft;let Ov=0;class Uv extends ft{constructor(e,t,i="bottom-right",n=128,s=2){super(),this.orthoCamera=new Mr(-1.8,1.8,1.8,-1.8,0,4),this.isViewHelper=!0,this.animating=!1,this.target=new x,this.viewport=new rt,this.offsetHeight=0,this.renderer=new Xf({canvas:document.createElement("canvas"),alpha:!0,antialias:!0,preserveDrawingBuffer:!1}),this.renderer.setPixelRatio(s),this.camera=e,this.domElement=t,this.orthoCamera.position.set(0,0,2),this.backgroundSphere=h3(),this.axesLines=c3(),this.spritePoints=u3(),this.add(this.backgroundSphere,this.axesLines,...this.spritePoints),this.domContainer=l3(i,n),this.domContainer.appendChild(this.renderer.domElement),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.domElement.parentElement.appendChild(this.domContainer),this.domRect=this.domContainer.getBoundingClientRect(),this.startListening(),this.update(),this.updateOrientation()}startListening(){this.domContainer.onpointermove=e=>this.onPointerMove(e),this.domContainer.onpointerleave=e=>this.onPointerLeave(e),this.domContainer.onclick=e=>this.handleClick(e)}onPointerMove(e){this.backgroundSphere.material.opacity=.4,this.handleHover(e),this.dispatchEvent({type:"update",event:e,change:"pointer"})}onPointerLeave(e){this.backgroundSphere.material.opacity=.2,fE(this.spritePoints),this.domContainer.style.cursor="",this.dispatchEvent({type:"update",event:e,change:"pointer"})}handleClick(e){const t=dE(e,this.domRect,this.orthoCamera,this.spritePoints);t&&this.setOrientation(t.userData.type)}handleHover(e){const t=dE(e,this.domRect,this.orthoCamera,this.spritePoints);fE(this.spritePoints),t?(t.material.map.offset.x=.5,t.scale.multiplyScalar(1.2),this.domContainer.style.cursor="pointer"):this.domContainer.style.cursor=""}render(){const e=a3.getDelta();this.animating&&this.animate(Math.min(e,1/30));const t=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.render(this,this.orthoCamera),this.renderer.autoClear=t}updateOrientation(e=!0){e&&(this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()),g3(this.spritePoints,this.camera)}update(){this.domRect=this.domContainer.getBoundingClientRect(),this.offsetHeight=this.domElement.offsetHeight,uE(this.camera,this.target),this.renderer.getViewport(this.viewport),this.updateOrientation()}animate(e){const t=e*o3;wm.rotateTowards(Bv,t),this.camera.position.set(0,0,1).applyQuaternion(wm).multiplyScalar(Ov).add(this.target),this.camera.quaternion.rotateTowards(pl,t),this.updateOrientation(),wm.angleTo(Bv)===0&&(this.animating=!1)}setOrientation(e){f3(this.camera,this.target,e),this.animating=!0,this.dispatchEvent({type:"update",change:"orientation"})}dispose(){this.axesLines.geometry.dispose(),this.axesLines.material.dispose(),this.backgroundSphere.geometry.dispose(),this.backgroundSphere.material.dispose(),this.spritePoints.forEach(e=>{e.material.map.dispose(),e.material.dispose()}),this.domContainer.remove()}}r3([so()],Uv.prototype,"animating");function l3(r,e){const t=document.createElement("div"),i=t.style;i.height=`${e}px`,i.width=`${e}px`,i.borderRadius="100%",i.position="absolute";const[n,s]=r.split("-");return i.transform="",i.left=s==="left"?"0":s==="center"?"50%":"",i.right=s==="right"?"0":"",i.transform+=s==="center"?"translateX(-50%)":"",i.top=n==="top"?"0":n==="bottom"?"":"50%",i.bottom=n==="bottom"?"0":"",i.transform+=n==="center"?"translateY(-50%)":"",t}function c3(){const e=Array(3).fill(0).map((n,s)=>[s?0:.9,s===1?.9:0,s===2?.9:0,0,0,0]).flat(),t=Array(6).fill(0).map((n,s)=>s<2?bm[0].toArray():s<4?bm[1].toArray():bm[2].toArray()).flat(),i=new Hs;return i.setPositions(e),i.setColors(t),new _a(i,new $c({linewidth:.02,vertexColors:!0}))}function h3(){const r=new Ds(1.6);return new ye(r,new ss({color:16777215,side:Rn,transparent:!0,opacity:.2,depthTest:!1}))}function u3(){const r=["x","y","z"];return Array(6).fill(0).map((e,t)=>{const i=t<3,n=i?"+":"-",s=r[t%3],a=bm[t%3],o=new Zf(d3(a,i?s:null));return o.userData.type=`${n}${s}`,o.scale.setScalar(i?.6:.4),o.position[s]=i?1.2:-1.2,o.renderOrder=1,o})}function d3(r,e=null){const t=document.createElement("canvas"),i=0,n=1,s=0;t.width=128*n+4*i+s*2,t.height=64*n+2*i+s*2;const a=t.getContext("2d",{alpha:!0});a.beginPath(),a.arc(32*n+i,32*n+i,32*n-i,0,2*Math.PI),a.closePath(),a.fillStyle=r.getStyle(),a.fill(),a.beginPath(),a.arc(32*n+i,32*n+i,35*n-i,0,2*Math.PI),a.closePath(),a.fillStyle="#"+r.getHexString()+"01",a.fill(),a.beginPath(),a.arc(96*n+i*3+s,32*n+i+s,32*n-i-s,0,2*Math.PI),a.closePath(),a.fillStyle="#FFF",a.fill(),a.beginPath(),a.arc(96*n+i*3+s,32*n+i+s,35+n-i-s,0,2*Math.PI),a.closePath(),a.fillStyle="#FFFFFF01",a.fill(),e!==null&&(a.font="bold calc(44px * "+n+") Arial",a.textAlign="center",a.fillStyle="#111",a.fillText(e.toUpperCase(),32*n+i,48*n+i),a.fillText(e.toUpperCase(),96*n+i*3+s,48*n+i+s));const o=new Wo(t);return o.wrapS=o.wrapT=Bn,o.repeat.x=.5,o.colorSpace=vt,o.minFilter=st,o.magFilter=st,o.generateMipmaps=!1,o.needsUpdate=!0,new du({map:o,toneMapped:!1,transparent:!0})}function f3(r,e,t){switch(t){case"+x":co.set(1,0,0),pl.setFromEuler(new Tt(0,Math.PI*.5,0));break;case"+y":co.set(0,1,0),pl.setFromEuler(new Tt(-Math.PI*.5,0,0));break;case"+z":co.set(0,0,1),pl.setFromEuler(new Tt);break;case"-x":co.set(-1,0,0),pl.setFromEuler(new Tt(0,-Math.PI*.5,0));break;case"-y":co.set(0,-1,0),pl.setFromEuler(new Tt(Math.PI*.5,0,0));break;case"-z":co.set(0,0,-1),pl.setFromEuler(new Tt(0,Math.PI,0));break;default:console.error("ViewHelper: Invalid axis.")}uE(r,e),p3(r,e)}function uE(r,e){Ov=r.position.distanceTo(e)}function p3(r,e){co.multiplyScalar(Ov).add(e),rd.position.copy(e),rd.lookAt(r.position),wm.copy(rd.quaternion),rd.lookAt(co),Bv.copy(rd.quaternion)}function m3(r,e,t){Lv.x=(r.clientX-e.left)/e.width*2-1,Lv.y=-((r.clientY-e.top)/e.height)*2+1,hE.setFromCamera(Lv,t)}function dE(r,e,t,i){m3(r,e,t);const n=hE.intersectObjects(i);return n.length?n[0].object:null}function fE(r){let e=r.length;for(;e--;){const t=e<3?.6:.4;r[e].scale.set(t,t,t),r[e].material.map.offset.x=1}}function g3(r,e){sd.set(0,0,1),sd.applyQuaternion(e.quaternion),sd.x>=0?(r[sE].material.opacity=1,r[oE].material.opacity=.5):(r[sE].material.opacity=.5,r[oE].material.opacity=1),sd.y>=0?(r[rE].material.opacity=1,r[lE].material.opacity=.5):(r[rE].material.opacity=.5,r[lE].material.opacity=1),sd.z>=0?(r[aE].material.opacity=1,r[cE].material.opacity=.5):(r[aE].material.opacity=.5,r[cE].material.opacity=1)}const X_=class X_ extends Su{constructor(){super(),this.type="CurvePath3"}};Bt.SerializableClasses.set("CurvePath3",X_);let Cm=X_;function xm(r,e){const t=e.getSize(new x);let i=1;if(r.isPerspectiveCamera&&t.length()>1e-4){const n=isFinite(r.aspect)?r.aspect:1,s=Math.max(1,r.fov)*(Math.PI/180),a=2*Math.atan(Math.tan(s/2)*n),o=t.z/2+Math.abs(t.x/2/Math.tan(a/2)),l=t.z/2+Math.abs(t.y/2/Math.tan(s/2));i=Math.max(o,l)}return i}const A3=r=>(e,t)=>t?.copy?.(e)??new r().copy(e),Zn=class Zn{static PrimitiveSerializer(e,t,i,n=1){return{priority:n,isType:s=>s?.[t],serialize:s=>{const a={[t]:!0};for(const o of i)a[o]=s[o];return a},deserialize:A3(e),type:t.startsWith("is")?t.slice(2):e.name}}static Init(){this._init||(this._init=!0,pa.prototype.isSpherical=!0,Bt.RegisterSerializer(...Zn.Primitives.map(e=>Zn.PrimitiveSerializer(e[0],e[1],e[2],e[3]))),Bt.RegisterSerializer(Zn.Texture),Bt.RegisterSerializer(Zn.Material),Bt.RegisterSerializer(Zn.RenderTarget),Bt.SerializableClasses.set("Shape",ar),Bt.SerializableClasses.set("Curve",Ps),Bt.SerializableClasses.set("CurvePath",Su),Bt.SerializableClasses.set("Path",Uc),Bt.SerializableClasses.set("ArcCurve",hp),Bt.SerializableClasses.set("CatmullRomCurve3",Oc),Bt.SerializableClasses.set("CubicBezierCurve",bu),Bt.SerializableClasses.set("CubicBezierCurve3",dp),Bt.SerializableClasses.set("EllipseCurve",qo),Bt.SerializableClasses.set("LineCurve",Xo),Bt.SerializableClasses.set("LineCurve3",Yo),Bt.SerializableClasses.set("QuadraticBezierCurve",wu),Bt.SerializableClasses.set("QuadraticBezierCurve3",Cu),Bt.SerializableClasses.set("SplineCurve",xu),Bt.SerializableClasses.set("AnimationClip",eo))}static MakeSerializable(e,t,i){e.prototype.serializableClassId=t,Bt.SerializableClasses.set(t,e),i&&Bt.TypeMap.set(e,i.map(n=>typeof n=="string"?[n,n]:n))}static Serialize(e,t,i=!1){return this._init||this.Init(),Bt.Serialize(e,t,i)}static Deserialize(e,t,i,n=!1){return this._init||this.Init(),Bt.Deserialize(e,t,i,n)}};Zn.Primitives=[[$,"isVector2",["x","y"],1],[x,"isVector3",["x","y","z"],1],[rt,"isVector4",["x","y","z","w"],1],[Qe,"isQuaternion",["x","y","z","w"],1],[Tt,"isEuler",["x","y","z","order"],1],[se,"isColor",["r","g","b"],1],[Fp,"isMatrix2",["elements"],1],[mt,"isMatrix3",["elements"],1],[pe,"isMatrix4",["elements"],1],[pa,"isSpherical",["radius","phi","theta"],1]],Zn.Texture={priority:2,isType:e=>e.isTexture||e.metadata?.type==="Texture",serialize:(e,t)=>{if(!e?.isTexture)throw new Error("Expected a texture");if(e.isRenderTargetTexture)return;if(t?.textures[e.uuid])return{uuid:e.uuid,resource:"textures"};const i=e.source.data,n=!e.isRenderTargetTexture&&e.userData.rootPath&&typeof e.userData.rootPath=="string"&&Hc(e.userData.rootPath);let s={};const a=e.userData;try{n&&e.source.data&&(e.userData.embedUrlImagePreviews?e.source.data=pm(e,16,e.flipY):e.source.data=null),e.userData={};const o={images:{}};s=e.toJSON(t||o),!t&&s.image&&(s.image=n&&!e.userData.embedUrlImagePreviews?void 0:o.images[s.image]),s.userData=Bt.Serialize(Fv({},a),t,!1)}catch(o){console.error("ThreeSerialization: Unable to serialize texture"),console.error(o)}return e.userData=a,n&&(t&&!e.userData.embedUrlImagePreviews&&delete t.images[e.source.uuid],e.source.data=i),t?.textures&&s&&!s.resource&&(t.textures[s.uuid]||(t.textures[s.uuid]=s),s={uuid:s.uuid,resource:"textures"}),s},deserialize:(e,t,i)=>{if(e.isTexture)return e;if(e.resource==="textures"&&i?.textures?.[e.uuid])return i.textures[e.uuid];console.warn("Cannot deserialize texture into object like primitive, since textures need to be loaded asynchronously. Trying with ObjectLoader. Load events might not work properly.",e,t);const n=i?._context.objectLoader??new Lp(i?._context.assetImporter?.loadingManager),s={...e};if(typeof s.image=="string"&&(i?.images?s.image=i.images[s.image]:console.error("ThreeSerialization: Cannot deserialize texture with image url without meta.images",s)),!s.image||typeof s.image=="string"||!s.image.isSource&&!s.image.url)return console.error("ThreeSerialization: Cannot deserialize texture",s),t;let a;i&&!s.image.isSource&&(i._context.imagePromises||(i._context.imagePromises=[]),i._context.imagePromises.push(new Promise(h=>{a=h})));const o=s.image.isSource?{[s.image.uuid]:s.image}:n.parseImages([s.image],a);s.image=Object.keys(o)[0],i?.images&&(i.images[s.image]=o[s.image]),s.userData&&(s.userData=Zn.Deserialize(s.userData,{},i));const l=n.parseTextures([s],o),c=Object.keys(l)[0];return!c||!l[c]?(console.error("ThreeSerialization: Cannot deserialize texture",s),t):(i?.textures&&(i.textures[c]=l[c]),l[c])}},Zn.SerializableMaterials=new Set,Zn.Material={priority:2,isType:e=>e.isMaterial||e.metadata?.type==="Material",serialize:(e,t)=>{if(!e?.isMaterial)throw new Error("Expected a material");if(t?.materials?.[e.uuid])return{uuid:e.uuid,resource:"materials"};const i=t??{textures:{},images:{}},n={},s={},a=Object.keys(e.constructor.MaterialProperties||e);for(const c of a){if(c.startsWith("__"))continue;const h=e[c];if(h?.isTexture){const u=Bt.Serialize(h,i);n[c]=u,s[c]=h,e[c]=u?{isTexture:!0,toJSON:()=>u}:null}}const o=e.userData;e.userData={};let l={};try{l=e.toJSON(t||i,!0),y3(l,o,t),l.userData.uuid=o.uuid,e.constructor.TYPE&&(l.type=e.constructor.TYPE);for(const c of Object.keys(l))l[c]===void 0&&delete l[c]}catch(c){console.error("ThreeSerialization: Unable to serialize material"),console.error(c)}e.userData=o;for(const[c,h]of Object.entries(s))e[c]=h,delete s[c];if(l)if(t){for(const[c,h]of Object.entries(n))h&&(l[c]=h);t.materials&&(t.materials[l.uuid]||(t.materials[l.uuid]=l),l={uuid:l.uuid,resource:"materials"})}else{for(const[c,h]of Object.entries(n))h&&(l[c]=h.uuid);l.textures=Object.values(i.textures),l.images=Object.values(i.images)}return l},deserialize:(e,t,i)=>{function n(m){if(m.isMaterial)return t?.isMaterial&&t.uuid===m.uuid?(t!==m&&typeof t.setValues=="function"&&(console.warn("ThreeSerialization: Material uuid already exists, copying values to old material"),t.setValues(m)),t):m}let s=n(e);if(s!==void 0)return s;if(e.resource==="materials"&&i?.materials?.[e.uuid]){if(s=n(i.materials[e.uuid]),s!==void 0)return s;console.error("ThreeSerialization: cannot find material in meta",e,s)}const a=e.type;if(!a)return console.error("ThreeSerialization: Cannot deserialize material without type",e),t;const o={...e};o.userData&&(o.userData=Bt.Deserialize(o.userData,void 0,i,!1));const l={};for(const[m,A]of Object.entries(o)){if(typeof A=="string"&&i?.textures?.[A]&&(o[m]=i.textures[A],l[m]=i.textures[A]),!A||!A.resource||typeof A.resource!="string")continue;const g=i?.[A.resource]?.[A.uuid];o[m]=g||null,A.resource==="textures"&&g?.isTexture&&(l[m]=g)}if((!t||!t.isMaterial||t.type!==a&&t.constructor?.TYPE!==a)&&(t&&Object.keys(t).length&&console.warn("ThreeSerialization: Material type mismatch during deserialize, creating a new material",t,o,a,t.constructor?.type),t=null),t&&(!o.uuid||t.uuid===o.uuid))return t.fromJSON?t.fromJSON(o,i,!0):t.setValues?t.setValues(o):console.error("ThreeSerialization: Cannot deserialize material, no fromJSON or setValues method",t,o),t;const c=e.isMaterial?void 0:e.uuid;let h=null;for(const m of Zn.SerializableMaterials)if(m.TYPE===a){h=m;break}if(!h){for(const m of Zn.SerializableMaterials)if(m.TypeAlias?.includes(a)){h=m;break}}if(h){const m=new h;if(m)return c&&an(m,"uuid",c,!0,!0),m.fromJSON?m.fromJSON(o,i,!0):m.setValues?m.setValues(o):console.error("ThreeSerialization: Cannot deserialize material, no fromJSON or setValues method",m,o),m}console.warn("Legacy three.js material deserialization");const u=new Bu;for(const[m,A]of Object.entries(l))o[m]=A.uuid;const d={...u.textures};u.setTextures(l);const p=u.parse(o);if(o.uuid&&an(p,"uuid",o.uuid,!0,!0),u.setTextures(d),s=n(p),s!==void 0)return s;console.error("ThreeSerialization: cannot deserialize material",e,s,p)}},Zn.RenderTarget={priority:2,isType:e=>e.isWebGLRenderTarget||e.metadata?.type==="RenderTarget",serialize:(e,t)=>{if(!e?.isWebGLRenderTarget||!e.uuid)throw new Error("Expected a IRenderTarget");if(t?.extras[e.uuid])return{uuid:e.uuid,resource:"extras"};const i=Array.isArray(e.texture)?e.texture[0]:e.texture;let n={metadata:{type:"RenderTarget"},uuid:e.uuid,width:e.width,height:e.height,depth:e.depth,sizeMultiplier:e.sizeMultiplier,count:Array.isArray(e.texture)?e.texture.length:void 0,isCubeRenderTarget:e.isWebGLCubeRenderTarget||void 0,isTemporary:e.isTemporary,textureName:Array.isArray(e.texture)?e.texture.map(s=>s.name):e.texture?.name,options:{wrapS:i?.wrapS,wrapT:i?.wrapT,magFilter:i?.magFilter,minFilter:i?.minFilter,format:i?.format,type:i?.type,anisotropy:i?.anisotropy,depthBuffer:!!e.depthBuffer,stencilBuffer:!!e.stencilBuffer,generateMipmaps:i?.generateMipmaps,depthTexture:!!e.depthTexture,colorSpace:i?.colorSpace,samples:e.samples}};return t?.extras&&(t.extras[n.uuid]||(t.extras[n.uuid]=n),n={uuid:n.uuid,resource:"extras"}),n},deserialize:(e,t,i)=>{if(t?.uuid===e.uuid)return t;if(e.isWebGLRenderTarget)return e;const n=i?._context.renderManager;if(!n)return console.error("ThreeSerialization: Cannot deserialize render target without render manager",e),t;if(e.isWebGLCubeRenderTarget||e.isTemporary)return console.warn("ThreeSerialization: Cannot deserialize WebGLCubeRenderTarget or temporary render target yet",e),t;const s=n.createTarget({sizeMultiplier:e.sizeMultiplier||void 0,size:e.sizeMultiplier?void 0:{width:e.width,height:e.height},textureCount:e.count,...e.options});if(e.textureName)if(Array.isArray(e.textureName)&&Array.isArray(s.texture))for(let a=0;a<e.textureName.length;a++)s.texture[a].name=e.textureName[a];else Array.isArray(s.texture)||(s.texture.name=Array.isArray(e.textureName)?e.textureName[0]:e.textureName);return s&&(s.uuid=e.uuid,i?.extras&&(i.extras[e.uuid]=s),s)}},Zn._init=!1;let ke=Zn;function ad(r,e,t=[]){if(!e)return r;for(const i of Object.keys(e)){if(t.includes(i)||i.startsWith("__"))continue;const n=e[i];if(typeof r[i]=="function"||typeof n=="function")continue;const s=!n||n.isTexture||n.isObject3D||n.isMaterial||n.isBufferGeometry||n.userDataSkipClone;!s&&typeof n.clone=="function"?r[i]=n.clone():!s&&(n.constructor===Object||Array.isArray(n))?r[i]=ad(Array.isArray(n)?[]:{},n,[]):r[i]=n}return r}function Fv(r,e,t=["uuid"]){return ad(r,e,t)}function Nv(r,e,t=["uuid"]){return ad(r,e,t)}function Sm(r,e,t=["uuid"]){return ad(r,e,t)}function y3(r,e,t){r.userData={},Nv(r.userData,e);const i=t||{textures:Object.fromEntries(r.textures?.map(n=>[n.uuid,n])||[]),images:Object.fromEntries(r.images?.map(n=>[n.uuid,n])||[])};r.userData=Bt.Serialize(r.userData,i),t||(Object.keys(i.textures).length>0&&(r.textures=Object.values(i.textures)),Object.keys(i.images).length>0&&(r.images=Object.values(i.images)))}function kv(r){Object.values(r).forEach(e=>{e&&Object.values(e).forEach(t=>{t.url&&(!(t.url.data instanceof ArrayBuffer)&&!Array.isArray(t.url.data)||(t.url.type==="Uint16Array"?(t.url.data instanceof Uint16Array||(t.url.data=new Uint16Array(t.url.data)),t.url.data="data:application/octet-stream;base64,"+Wp(t.url.data.buffer)):t.url.type==="Uint8Array"?(t.url.data instanceof Uint8Array||(t.url.data=new Uint8Array(t.url.data)),t.url.data="data:application/octet-stream;base64,"+Wp(t.url.data.buffer)):t.url.data instanceof ArrayBuffer?t.url.data="data:application/octet-stream;base64,"+Wp(t.url.data.buffer):console.warn("Unsupported buffer type",t.url.type)))})})}function pE(r){Object.values(r).forEach(e=>{e&&Object.values(e).forEach(t=>{if(!t||!t.url||typeof t.url.data!="string")return;const i=t.url.data.match(/^data:.*;base64,(.*)$/);i?.[1]?t.url.data=Qy(i?.[1]):(t.url.type!=="Uint8Array"&&console.error("ThreeSerialization: Unsupported buffer type string for ",t.url.type,"use base64"),t.url.data=new TextEncoder().encode(t.url.data).buffer)})})}function Fr(r){return{geometries:{...r?.geometries},materials:{...r?.materials},textures:{...r?.textures},images:{...r?.images},shapes:{...r?.shapes},skeletons:{...r?.skeletons},animations:{...r?.animations},extras:{...r?.extras},typed:{...r?.typed},_context:{}}}class Em{static async ImportMeta(e,t){if(e.__isLoadedResources)return e;const i=Gv();i.__isLoadedResources=!0,i._context=e._context,pE(e);const n=e._context.assetImporter;if(!n)throw new Error("assetImporter not found in meta context, which is required for import meta.");const s=e._context.objectLoader||new Lp(n.loadingManager);i.animations=e.animations?s.parseAnimations(Object.values(e.animations)):{},t&&t.animations&&(i.animations={...i.animations,...t.animations}),i.shapes=e.shapes?s.parseShapes(Object.values(e.shapes)):{},t&&t.shapes&&(i.shapes={...i.shapes,...t.shapes}),i.geometries=e.geometries?s.parseGeometries(Object.values(e.geometries),i.shapes):{},t&&t.geometries&&(i.geometries={...i.geometries,...t.geometries}),i.images=e.images?await s.parseImagesAsync(Object.values(e.images)):{},t&&t.images&&(i.images={...i.images,...t.images}),Array.isArray(e.textures)&&(console.error("ThreeSerialization: TODO: check file format"),e.textures=e.textures.reduce((c,h)=>(h&&(c[h.uuid]=h),c))),await Em.LoadRootPathTextures({textures:e.textures,images:i.images},n);const a=[];for(const c of Object.values(e.textures)){const h={...c};h.userData&&(h.userData=ke.Deserialize(h.userData,{},i)),a.push(h)}i.textures=e.textures?s.parseTextures(a,i.images):{};for(const c of Object.keys(i.textures)){let h=i.textures[c];if(h){if(h.source.__texCtor){const u=new h.source.__texCtor(h.source.data);if(!u||typeof u.copy!="function")continue;u.copy(h),delete h.source.__texCtor,i.textures[c]=u,h=u}if(h.source.data instanceof HTMLCanvasElement&&!h.isCanvasTexture){const u=new Wo(h.source.data).copy(h);i.textures[c]=u,h=u}}}const o={...i.textures};for(const c of Object.values(e.textures))c.rootPathPromise?.then(h=>{if(!h)return;const u=o[c.uuid];u.dispose(),u.source=h,u.source.needsUpdate=!0,u.needsUpdate=!0});for(const c of Object.entries(i.textures))c[1]=await n.processRawSingle(c[1],{}),c[1]?i.textures[c[0]]=c[1]:delete i.textures[c[0]];t&&t.textures&&(i.textures={...i.textures,...t.textures});const l=e.materials?Object.values(e.materials):[];i.materials={};for(const c of l)c?.uuid&&(i.materials[c.uuid]=ke.Deserialize(c,void 0,i));if(t&&t.materials&&(i.materials={...i.materials,...t.materials}),e.object&&(i.object=s.parseObject(e.object,i.geometries,i.materials,i.textures,i.animations),e.skeletons&&(i.skeletons=s.parseSkeletons(Object.values(e.skeletons),i.object),s.bindSkeletons(i.object,i.skeletons))),e.extras){i.extras=e.extras;for(const c of Object.values(e.extras))if(c.uuid){if(!c.url){i.extras[c.uuid]=ke.Deserialize(c,void 0,i);continue}if(typeof c.url=="string"){const h=await n.importSingle(c.url,c.userData?.rootPathOptions||{});h&&(i.extras[c.uuid]=h)}else if(c.url.data){const h=new File([Vx(c.url.type,c.url.data)],c.url.path),u=await n.importSingle({path:h.name,file:h},c.userData?.rootPathOptions||{},void 0,!1);u&&(i.extras[c.uuid]=u)}else console.warn("invalid URL type while loading extra resource")}}if(t&&t.extras&&(i.extras={...i.extras,...t.extras}),i.typed={},e.typed)for(const[c,h]of Object.entries(e.typed))if(typeof h.rootPath=="string"&&h.external){const u=await n.importSingle(h.rootPath,h.rootPathOptions||{});u&&(i.typed[c]=u)}else i.typed[c]=ke.Deserialize(h,void 0,i);return t&&t.typed&&(i.typed={...i.typed,...t.typed}),i}static async LoadRootPathTextures({textures:e,images:t},i,n=!0){const s=[];for(const a of Array.isArray(e)?e:Object.values(e??{})){const o=a?.userData?.rootPath,l=n&&a.image&&t[a.image];if(!o)continue;const c=i.importSingle(o,a.userData.rootPathOptions||{}).then(h=>{const u=h?.source;if(!h||!h.isTexture||!u){console.error("AssetImporter: Imported rootPath is not a Texture",o,h);return}const d=new na(u.data);return a.image&&(d.uuid=a.image),a.image=d.uuid,h.constructor!==Rt&&h.constructor!==As&&h.constructor!==_c&&(d.__texCtor=h.constructor),l||(t[d.uuid]=d),h.dispose(),d}).catch(h=>(console.error("ThreeSerialization: Error loading texture from rootPath",a.userData.rootPath),console.error(h),delete a.userData.rootPath,null));l?a.rootPathPromise=c:s.push(c)}await Promise.allSettled(s)}}function od(r){if(!r)return{};const e={...r};return e._context&&delete e._context,e}function v3(r,e){for(const t of Object.keys(e))t!=="object"&&(r[t]||(r[t]={}),Object.assign(r[t],e[t]));return r}function Gv(r,e){return{...r,...Fr(r),_context:{assetManager:e?.assetManager,assetImporter:e?.assetManager.importer,renderManager:e?.renderManager,viewer:e}}}function zv(r){const e=new Blob([JSON.stringify(r)],{type:"application/json"});return e.ext="json",e}function mE(r,e,t,i){if(e?.extras[r.uuid])return{uuid:r.uuid,resource:"extras"};let n="";if(r.source?._sourceImgBuffer||r.__sourceBuffer){const a=new Uint8Array(r.source?._sourceImgBuffer||r.__sourceBuffer),o=i||r.userData.mimeType||"";n={data:Array.from(a),type:a.constructor.name,path:r.userData.__sourceBlob?.name||r.userData.rootPath||"file."+o.split("/")[1]},o&&(n.mimeType=o)}else r.userData.rootPath?n=r.userData.rootPath:console.error("ThreeSerialization: Unable to serialize LUT texture, not loaded through asset manager.");const s={uuid:r.uuid,url:n,userData:Fv({},r.userData),type:r.type,name:t||r.name};return e?.extras?(e.extras[r.uuid]=s,{uuid:r.uuid,resource:"extras"}):s}function gE(r,e){const t={},i=Array.isArray(e)?e:[];for(const n of i){const s=n.startsWith("userData.");let a;s?a=Gu(n.slice(9),r.userData,!1):a=r[n],a!==void 0&&(t[n]=a)}return t}function Mm(r,e){for(const t of Object.keys(r)){const i=r[t];if(!t.startsWith("userData."))e[t]=i;else{const s=e.userData,a=t.split("."),o=a.slice(1,-1),l=a.length&&o.length?Gu(o,s,!1):void 0;if(l!==void 0){const c=a[a.length-1];l[c]=i}else console.warn("ThreeSerialization: setSProps: invalid sProperty",t,"in",e)}}}const _3=!0,AE="shaderReplaceString: str must be passed if str is a RegExp and append/prepend is true";function At(r,e,t,{replaceAll:i=!1,prepend:n=!1,append:s=!1,str:a=void 0,warn:o=!0}={}){const l=typeof e=="string";if(o&&_3&&(l?!r.includes(e):!e.test(r)))return console.error(`${e} not found in shader`),r;let c=t;if(a=a??(l?e:void 0),n){if(typeof a!="string")throw new Error(AE);c=t+a}else if(s){if(typeof a!="string")throw new Error(AE);c=a+t}return i?r.replaceAll(e,c):r.replace(e,c)}function yE(r,e=0){const t=b3(r.byteLength);if(t!==r.byteLength){const i=new Uint8Array(t);if(i.set(new Uint8Array(r)),e!==0)for(let n=r.byteLength;n<t;n++)i[n]=e;return i.buffer}return r.buffer}function b3(r){return Math.ceil(r/4)*4}const vE=12,w3=1179937895,C3=2,_E=8,x3=1313821514,S3=5130562;function bE(r,e){const t=yE(r),i=new DataView(new ArrayBuffer(_E));i.setUint32(0,t.byteLength,!0),i.setUint32(4,S3,!0);const n=new TextEncoder().encode(JSON.stringify(e||{})),s=yE(n,32),a=new DataView(new ArrayBuffer(_E));a.setUint32(0,s.byteLength,!0),a.setUint32(4,x3,!0);const o=new ArrayBuffer(vE),l=new DataView(o);l.setUint32(0,w3,!0),l.setUint32(4,C3,!0);const c=vE+a.byteLength+s.byteLength+i.byteLength+t.byteLength;l.setUint32(8,c,!0);const h=new Blob([o,a,s,i,t],{type:"model/gltf+binary"});return h.ext="glb",h}function wE(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t}var CE=function(){};const Vv=(r,e,t)=>Math.min(Math.max(t,r),e),Hv=.001,E3=.01,M3=10,T3=.05,I3=1;function P3({duration:r=800,bounce:e=.25,velocity:t=0,mass:i=1}){let n,s,a=1-e;a=Vv(T3,I3,a),r=Vv(E3,M3,r/1e3),a<1?(n=c=>{const h=c*a,u=h*r,d=h-t,p=Qv(c,a),m=Math.exp(-u);return Hv-d/p*m},s=c=>{const u=c*a*r,d=u*t+t,p=Math.pow(a,2)*Math.pow(c,2)*r,m=Math.exp(-u),A=Qv(Math.pow(c,2),a);return(-n(c)+Hv>0?-1:1)*((d-p)*m)/A}):(n=c=>{const h=Math.exp(-c*r),u=(c-t)*r+1;return-Hv+h*u},s=c=>{const h=Math.exp(-c*r),u=(t-c)*(r*r);return h*u});const o=5/r,l=R3(n,s,o);if(r=r*1e3,isNaN(l))return{stiffness:100,damping:10,duration:r};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:a*2*Math.sqrt(i*c),duration:r}}}const D3=12;function R3(r,e,t){let i=t;for(let n=1;n<D3;n++)i=i-r(i)/e(i);return i}function Qv(r,e){return r*Math.sqrt(1-e*e)}const B3=["duration","bounce"],L3=["stiffness","damping","mass"];function xE(r,e){return e.some(t=>r[t]!==void 0)}function O3(r){let e=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},r);if(!xE(r,L3)&&xE(r,B3)){const t=P3(r);e=Object.assign(Object.assign(Object.assign({},e),t),{velocity:0,mass:1}),e.isResolvedFromDuration=!0}return e}function jv(r){var{from:e=0,to:t=1,restSpeed:i=2,restDelta:n}=r,s=wE(r,["from","to","restSpeed","restDelta"]);const a={done:!1,value:e};let{stiffness:o,damping:l,mass:c,velocity:h,duration:u,isResolvedFromDuration:d}=O3(s),p=SE,m=SE;function A(){const g=h?-(h/1e3):0,y=t-e,_=l/(2*Math.sqrt(o*c)),v=Math.sqrt(o/c)/1e3;if(n===void 0&&(n=Math.min(Math.abs(t-e)/100,.4)),_<1){const b=Qv(v,_);p=T=>{const E=Math.exp(-_*v*T);return t-E*((g+_*v*y)/b*Math.sin(b*T)+y*Math.cos(b*T))},m=T=>{const E=Math.exp(-_*v*T);return _*v*E*(Math.sin(b*T)*(g+_*v*y)/b+y*Math.cos(b*T))-E*(Math.cos(b*T)*(g+_*v*y)-b*y*Math.sin(b*T))}}else if(_===1)p=b=>t-Math.exp(-v*b)*(y+(g+v*y)*b);else{const b=v*Math.sqrt(_*_-1);p=T=>{const E=Math.exp(-_*v*T),M=Math.min(b*T,300);return t-E*((g+_*v*y)*Math.sinh(M)+b*y*Math.cosh(M))/b}}}return A(),{next:g=>{const y=p(g);if(d)a.done=g>=u;else{const _=m(g)*1e3,v=Math.abs(_)<=i,b=Math.abs(t-y)<=n;a.done=v&&b}return a.value=a.done?t:y,a},flipTarget:()=>{h=-h,[e,t]=[t,e],A()}}}jv.needsInterpolation=(r,e)=>typeof r=="string"||typeof e=="string";const SE=r=>0,EE=(r,e,t)=>{const i=e-r;return i===0?1:(t-r)/i},Wv=(r,e,t)=>-t*r+t*e+r,ME=(r,e)=>t=>Math.max(Math.min(t,e),r),ld=r=>r%1?Number(r.toFixed(5)):r,Tm=/(-)?([\d]*\.?[\d])+/g,qv=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,U3=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function cd(r){return typeof r=="string"}const Im={test:r=>typeof r=="number",parse:parseFloat,transform:r=>r},TE=Object.assign(Object.assign({},Im),{transform:ME(0,1)});Object.assign(Object.assign({},Im),{default:1});const hd=(r=>({test:e=>cd(e)&&e.endsWith(r)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${r}`}))("%");Object.assign(Object.assign({},hd),{parse:r=>hd.parse(r)/100,transform:r=>hd.transform(r*100)});const Xv=(r,e)=>t=>!!(cd(t)&&U3.test(t)&&t.startsWith(r)||e&&Object.prototype.hasOwnProperty.call(t,e)),IE=(r,e,t)=>i=>{if(!cd(i))return i;const[n,s,a,o]=i.match(Tm);return{[r]:parseFloat(n),[e]:parseFloat(s),[t]:parseFloat(a),alpha:o!==void 0?parseFloat(o):1}},ml={test:Xv("hsl","hue"),parse:IE("hue","saturation","lightness"),transform:({hue:r,saturation:e,lightness:t,alpha:i=1})=>"hsla("+Math.round(r)+", "+hd.transform(ld(e))+", "+hd.transform(ld(t))+", "+ld(TE.transform(i))+")"},F3=ME(0,255),Yv=Object.assign(Object.assign({},Im),{transform:r=>Math.round(F3(r))}),ho={test:Xv("rgb","red"),parse:IE("red","green","blue"),transform:({red:r,green:e,blue:t,alpha:i=1})=>"rgba("+Yv.transform(r)+", "+Yv.transform(e)+", "+Yv.transform(t)+", "+ld(TE.transform(i))+")"};function N3(r){let e="",t="",i="",n="";return r.length>5?(e=r.substr(1,2),t=r.substr(3,2),i=r.substr(5,2),n=r.substr(7,2)):(e=r.substr(1,1),t=r.substr(2,1),i=r.substr(3,1),n=r.substr(4,1),e+=e,t+=t,i+=i,n+=n),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:n?parseInt(n,16)/255:1}}const $v={test:Xv("#"),parse:N3,transform:ho.transform},Pm={test:r=>ho.test(r)||$v.test(r)||ml.test(r),parse:r=>ho.test(r)?ho.parse(r):ml.test(r)?ml.parse(r):$v.parse(r),transform:r=>cd(r)?r:r.hasOwnProperty("red")?ho.transform(r):ml.transform(r)},PE="${c}",DE="${n}";function k3(r){var e,t,i,n;return isNaN(r)&&cd(r)&&((t=(e=r.match(Tm))===null||e===void 0?void 0:e.length)!==null&&t!==void 0?t:0)+((n=(i=r.match(qv))===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0)>0}function RE(r){typeof r=="number"&&(r=`${r}`);const e=[];let t=0;const i=r.match(qv);i&&(t=i.length,r=r.replace(qv,PE),e.push(...i.map(Pm.parse)));const n=r.match(Tm);return n&&(r=r.replace(Tm,DE),e.push(...n.map(Im.parse))),{values:e,numColors:t,tokenised:r}}function BE(r){return RE(r).values}function LE(r){const{values:e,numColors:t,tokenised:i}=RE(r),n=e.length;return s=>{let a=i;for(let o=0;o<n;o++)a=a.replace(o<t?PE:DE,o<t?Pm.transform(s[o]):ld(s[o]));return a}}const G3=r=>typeof r=="number"?0:r;function z3(r){const e=BE(r);return LE(r)(e.map(G3))}const OE={test:k3,parse:BE,createTransformer:LE,getAnimatableNone:z3};function Kv(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*(2/3-t)*6:r}function UE({hue:r,saturation:e,lightness:t,alpha:i}){r/=360,e/=100,t/=100;let n=0,s=0,a=0;if(!e)n=s=a=t;else{const o=t<.5?t*(1+e):t+e-t*e,l=2*t-o;n=Kv(l,o,r+1/3),s=Kv(l,o,r),a=Kv(l,o,r-1/3)}return{red:Math.round(n*255),green:Math.round(s*255),blue:Math.round(a*255),alpha:i}}const V3=(r,e,t)=>{const i=r*r,n=e*e;return Math.sqrt(Math.max(0,t*(n-i)+i))},H3=[$v,ho,ml],FE=r=>H3.find(e=>e.test(r)),NE=(r,e)=>{let t=FE(r),i=FE(e),n=t.parse(r),s=i.parse(e);t===ml&&(n=UE(n),t=ho),i===ml&&(s=UE(s),i=ho);const a=Object.assign({},n);return o=>{for(const l in a)l!=="alpha"&&(a[l]=V3(n[l],s[l],o));return a.alpha=Wv(n.alpha,s.alpha,o),t.transform(a)}},Q3=r=>typeof r=="number",j3=(r,e)=>t=>e(r(t)),kE=(...r)=>r.reduce(j3);function GE(r,e){return Q3(r)?t=>Wv(r,e,t):Pm.test(r)?NE(r,e):HE(r,e)}const zE=(r,e)=>{const t=[...r],i=t.length,n=r.map((s,a)=>GE(s,e[a]));return s=>{for(let a=0;a<i;a++)t[a]=n[a](s);return t}},W3=(r,e)=>{const t=Object.assign(Object.assign({},r),e),i={};for(const n in t)r[n]!==void 0&&e[n]!==void 0&&(i[n]=GE(r[n],e[n]));return n=>{for(const s in i)t[s]=i[s](n);return t}};function VE(r){const e=OE.parse(r),t=e.length;let i=0,n=0,s=0;for(let a=0;a<t;a++)i||typeof e[a]=="number"?i++:e[a].hue!==void 0?s++:n++;return{parsed:e,numNumbers:i,numRGB:n,numHSL:s}}const HE=(r,e)=>{const t=OE.createTransformer(e),i=VE(r),n=VE(e);return i.numHSL===n.numHSL&&i.numRGB===n.numRGB&&i.numNumbers>=n.numNumbers?kE(zE(i.parsed,n.parsed),t):a=>`${a>0?e:r}`},q3=(r,e)=>t=>Wv(r,e,t);function X3(r){if(typeof r=="number")return q3;if(typeof r=="string")return Pm.test(r)?NE:HE;if(Array.isArray(r))return zE;if(typeof r=="object")return W3}function Y3(r,e,t){const i=[],n=t||X3(r[0]),s=r.length-1;for(let a=0;a<s;a++){let o=n(r[a],r[a+1]);if(e){const l=Array.isArray(e)?e[a]:e;o=kE(l,o)}i.push(o)}return i}function $3([r,e],[t]){return i=>t(EE(r,e,i))}function K3(r,e){const t=r.length,i=t-1;return n=>{let s=0,a=!1;if(n<=r[0]?a=!0:n>=r[i]&&(s=i-1,a=!0),!a){let l=1;for(;l<t&&!(r[l]>n||l===i);l++);s=l-1}const o=EE(r[s],r[s+1],n);return e[s](o)}}function QE(r,e,{clamp:t=!0,ease:i,mixer:n}={}){const s=r.length;CE(s===e.length),CE(!i||!Array.isArray(i)||i.length===s-1),r[0]>r[s-1]&&(r=[].concat(r),e=[].concat(e),r.reverse(),e.reverse());const a=Y3(e,i,n),o=s===2?$3(r,a):K3(r,a);return t?l=>o(Vv(r[0],r[s-1],l)):o}const Dm=r=>e=>1-r(1-e),Jv=r=>e=>e<=.5?r(2*e)/2:(2-r(2*(1-e)))/2,J3=r=>e=>Math.pow(e,r),jE=r=>e=>e*e*((r+1)*e-r),Z3=r=>{const e=jE(r);return t=>(t*=2)<1?.5*e(t):.5*(2-Math.pow(2,-10*(t-1)))},WE=1.525,eN=4/11,tN=8/11,iN=9/10,nN=r=>r,Zv=J3(2),sN=Dm(Zv),qE=Jv(Zv),XE=r=>1-Math.sin(Math.acos(r)),YE=Dm(XE),rN=Jv(YE),e0=jE(WE),aN=Dm(e0),oN=Jv(e0),lN=Z3(WE),cN=4356/361,hN=35442/1805,uN=16061/1805,Rm=r=>{if(r===1||r===0)return r;const e=r*r;return r<eN?7.5625*e:r<tN?9.075*e-9.9*r+3.4:r<iN?cN*e-hN*r+uN:10.8*r*r-20.52*r+10.72},dN=Dm(Rm),fN=r=>r<.5?.5*(1-Rm(1-r*2)):.5*Rm(r*2-1)+.5;function pN(r,e){return r.map(()=>e||qE).splice(0,r.length-1)}function mN(r){const e=r.length;return r.map((t,i)=>i!==0?i/(e-1):0)}function gN(r,e){return r.map(t=>t*e)}function ud({from:r=0,to:e=1,ease:t,offset:i,duration:n=300}){const s={done:!1,value:r},a=Array.isArray(e)?e:[r,e],o=gN(i&&i.length===a.length?i:mN(a),n);function l(){return QE(o,a,{ease:Array.isArray(t)?t:pN(a,t)})}let c=l();return{next:h=>(s.value=c(h),s.done=h>=n,s),flipTarget:()=>{a.reverse(),c=l()}}}function AN({velocity:r=0,from:e=0,power:t=.8,timeConstant:i=350,restDelta:n=.5,modifyTarget:s}){const a={done:!1,value:e};let o=t*r;const l=e+o,c=s===void 0?l:s(l);return c!==l&&(o=c-e),{next:h=>{const u=-o*Math.exp(-h/i);return a.done=!(u>n||u<-n),a.value=a.done?c:c+u,a},flipTarget:()=>{}}}const $E={keyframes:ud,spring:jv,decay:AN};function yN(r){if(Array.isArray(r.to))return ud;if($E[r.type])return $E[r.type];const e=new Set(Object.keys(r));return e.has("ease")||e.has("duration")&&!e.has("dampingRatio")?ud:e.has("dampingRatio")||e.has("stiffness")||e.has("mass")||e.has("damping")||e.has("restSpeed")||e.has("restDelta")?jv:ud}const KE=1/60*1e3,vN=typeof performance<"u"?()=>performance.now():()=>Date.now(),JE=typeof window<"u"?r=>window.requestAnimationFrame(r):r=>setTimeout(()=>r(vN()),KE);function _N(r){let e=[],t=[],i=0,n=!1,s=!1;const a=new WeakSet,o={schedule:(l,c=!1,h=!1)=>{const u=h&&n,d=u?e:t;return c&&a.add(l),d.indexOf(l)===-1&&(d.push(l),u&&n&&(i=e.length)),l},cancel:l=>{const c=t.indexOf(l);c!==-1&&t.splice(c,1),a.delete(l)},process:l=>{if(n){s=!0;return}if(n=!0,[e,t]=[t,e],t.length=0,i=e.length,i)for(let c=0;c<i;c++){const h=e[c];h(l),a.has(h)&&(o.schedule(h),r())}n=!1,s&&(s=!1,o.process(l))}};return o}const bN=40;let t0=!0,dd=!1,i0=!1;const fd={delta:0,timestamp:0},pd=["read","update","preRender","render","postRender"],Bm=pd.reduce((r,e)=>(r[e]=_N(()=>dd=!0),r),{}),wN=pd.reduce((r,e)=>{const t=Bm[e];return r[e]=(i,n=!1,s=!1)=>(dd||SN(),t.schedule(i,n,s)),r},{}),CN=pd.reduce((r,e)=>(r[e]=Bm[e].cancel,r),{});pd.reduce((r,e)=>(r[e]=()=>Bm[e].process(fd),r),{});const xN=r=>Bm[r].process(fd),ZE=r=>{dd=!1,fd.delta=t0?KE:Math.max(Math.min(r-fd.timestamp,bN),1),fd.timestamp=r,i0=!0,pd.forEach(xN),i0=!1,dd&&(t0=!1,JE(ZE))},SN=()=>{dd=!0,t0=!0,i0||JE(ZE)};function eM(r,e,t=0){return r-e-t}function EN(r,e,t=0,i=!0){return i?eM(e+-r,e,t):e-(r-e)+t}function MN(r,e,t,i){return i?r>=e+t:r<=-t}const TN=r=>{const e=({delta:t})=>r(t);return{start:()=>wN.update(e,!0),stop:()=>CN.update(e)}};function n0(r){var e,t,{from:i,autoplay:n=!0,driver:s=TN,elapsed:a=0,repeat:o=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:u,onComplete:d,onRepeat:p,onUpdate:m}=r,A=wE(r,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:g}=A,y,_=0,v=A.duration,b,T=!1,E=!0,M;const S=yN(A);!((t=(e=S).needsInterpolation)===null||t===void 0)&&t.call(e,i,g)&&(M=QE([0,100],[i,g],{clamp:!1}),i=0,g=100);const w=S(Object.assign(Object.assign({},A),{from:i,to:g}));function C(){_++,l==="reverse"?(E=_%2===0,a=EN(a,v,c,E)):(a=eM(a,v,c),l==="mirror"&&w.flipTarget()),T=!1,p&&p()}function D(){y.stop(),d&&d()}function O(G){E||(G=-G),a+=G;const j=Math.max(0,a);if(!T||j<=(v||0)){const W=w.next(j);b=W.value,M&&(b=M(b)),T=E?W.done:a<=0}m?.(b),T&&(_===0&&(v??(v=a)),_<o?MN(a,v,c,E)&&C():D())}function F(){h?.(),y=s(O),y.start()}return n&&F(),{stop:()=>{u?.(),y.stop()}}}const Kc={linear:nN,easeIn:Zv,easeOut:sN,easeInOut:qE,circIn:XE,circOut:YE,circInOut:rN,backIn:e0,backOut:aN,backInOut:oN,anticipate:lN,bounceOut:Rm,bounceIn:dN,bounceInOut:fN,easeInOutSine:r=>-(Math.cos(Math.PI*r)-1)/2};function s0(r,e,t){const i=r[e],n=()=>{t?.()},s=typeof i=="boolean";return i&&i.isColor?a=>{i.set(a),n()}:i&&typeof i.copy=="function"?a=>{i.copy(a),n()}:a=>{r[e]=s?!!a:a,n()}}async function IN(r,e,t,i,n=!1){e in r||console.error("invalid key",e,r);const s=s0(r,e),a=n||t.from===void 0?r[e]:t.from,o=l=>{s(l),t.onUpdate&&t.onUpdate(l)};if(typeof a=="boolean"){const{duration:l}=t;return jn(l??0).then(()=>o(t.to))}else return typeof t.to=="function"&&(t={...t,to:t.to(a,r)}),tM({...t,from:a,onUpdate:o},i)}async function tM(r,e){const t=r.onComplete,i=r.onStop,n=r.onEnd;return r={...r},new Promise((s,a)=>{const o=()=>{try{n?.()}catch(c){return a(c),!1}return!0};r.onComplete=()=>{try{t?.()}catch(c){if(!o())return;a(c);return}o()&&s()},r.onStop=()=>{try{i?.()}catch(c){if(!o())return;a(c);return}o()&&s()};const l=n0(r);e&&e.push(l)})}function r0(r,e,t){const i=e-r;return i>=Math.PI?r+(i-Math.PI*2)*t:i<=-Math.PI?r+(i+Math.PI*2)*t:r+i*t}const Lm=Ut.lerp;function PN({from:r,autoplay:e=!0,driver:t,elapsed:i=0,onPlay:n,onStop:s,onComplete:a,onUpdate:o,delay:l=0,canComplete:c=!0,...h}){const{to:u}=h;let d;const p=h.duration||0;let m,A=!1;const g=ud({...h,from:r,to:u});function y(){d.stop(),a&&a()}function _(b){const T=i>=l;if(i+=b,i<l&&!T)return;const E=Math.max(0,i-l);if(!A||E<=(p||0)){const M=g.next(E);m=M.value,A=M.done}o?.(m),A&&c&&y()}function v(){n?.(),d=t(_),d.start()}return e&&v(),{stop:()=>{s?.(),d.stop()}}}function a0(r){const e=r.position.clone();e.sub(r.target);const t=new pa().setFromVector3(e);return t.makeSafe(),t}function iM(r,e){const t=r.parent,i=r.target.clone(),n=r.getWorldPosition(new x),s={target:i,zoom:r.zoom,spherical:a0({position:n,target:i})},a={position:new x,target:new x,zoom:1,spherical:new pa},o={position:e.position,target:e.target,zoom:e.zoom,spherical:a0(e)};function l(){r.position.copy(t?t.worldToLocal(a.position):a.position),r.target.copy(a.target),r.zoom=a.zoom,r.setDirty()}return{from:0,to:1,onUpdate:c=>{a.spherical.phi=r0(s.spherical.phi,o.spherical.phi,c),a.spherical.theta=r0(s.spherical.theta,o.spherical.theta,c),a.spherical.radius=Lm(s.spherical.radius,o.spherical.radius,c),a.target.copy(s.target).lerp(o.target,c),a.position.setFromSpherical(a.spherical),a.position.add(a.target),a.zoom=Lm(s.zoom,o.zoom,c),l()},onComplete:()=>{a.position.copy(o.position),a.target.copy(o.target),a.zoom=o.zoom,l()},onStop:()=>{throw new Error("Animation Stopped")}}}function nM(r,e){const t=r.parent,i=r.target.clone(),n=r.getWorldPosition(new x),s=r.getWorldQuaternion(new Qe),a={position:n,target:i,quaternion:s,zoom:r.zoom},o={position:new x,target:new x,quaternion:new Qe,zoom:1},l=e;function c(){r.position.copy(t?t.worldToLocal(o.position):o.position),r.target.copy(o.target),r.quaternion.copy(t?WS(t,o.quaternion,r.quaternion):o.quaternion),r.zoom=o.zoom,r.setDirty()}return{from:0,to:1,onUpdate:h=>{o.position.lerpVectors(a.position,l.position,h),o.target.lerpVectors(a.target,l.target,h),o.quaternion.slerpQuaternions(a.quaternion,l.quaternion,h),o.zoom=Lm(a.zoom,l.zoom,h),c()},onComplete:()=>{o.position.copy(l.position),o.target.copy(l.target),o.quaternion.copy(l.quaternion),o.zoom=l.zoom,c()},onStop:()=>{throw new Error("Animation Stopped")}}}function Om(r,e,t){return typeof e=="number"&&typeof t=="number"?Jc(r,e,t):typeof e?.r=="number"&&typeof t?.r=="number"?new se().set(Jc(r.from?{...r,from:r.from.r}:r,e.r,t.r),Jc(r.from?{...r,from:r.from.g}:r,e.g,t.g),Jc(r.from?{...r,from:r.from.b}:r,e.b,t.b)):e?.toArray&&t?.toArray&&e.clone&&e.fromArray?o0(r,e,t):r.t>=1?t:e}function Jc(r,e,t){const{t:i,dt:n}=r;let s;if(i<=0)s=r.from!==void 0?r.from:e;else if(i>=1)s=t;else if(r.from!==void 0)s=r.from*(1-i)+t*i;else{const a=1-i,o=Math.max(0,Math.min(n,a)/a);s=e+(t-e)*o}return s}function o0(r,e,t){const i=e.toArray(),n=t.toArray(),s=r.from?r.from.toArray():void 0,a=i.map((l,c)=>Om(s?{...r,from:s[c]}:r,l,n[c]));return e.clone().fromArray(a)}function sM(r,e,t){if(!r.rm)return console.warn("MaterialManager: RenderManager is required for interpolating textures"),t;const{t:i,dt:n}=r;let s;const a=r.from!==void 0?r.from:e;if(i<=0||i>.99||a===t){s=i<=0?a:t;let o;e&&e.userData?._lerpTexture&&e.isRenderTargetTexture&&(o=e._target),o&&r.rm.releaseTempTarget(o)}else{const o=a||gm;let l=!1,c;if(e&&e.userData?._lerpTexture&&e.isRenderTargetTexture)c=e._target;else{const h=a||t||gm,u={width:h.image?.width||h.image?.naturalWidth||h.image?.videoWidth||1,height:h.image?.height||h.image?.naturalHeight||h.image?.videoHeight||1};c=r.rm.getTempTarget({size:u,colorSpace:h.colorSpace,type:h.type,format:h.format,generateMipmaps:h.generateMipmaps,minFilter:h.minFilter,magFilter:h.magFilter,wrapS:h.wrapS,wrapT:h.wrapT}),c.texture.userData._lerpTexture=!0,l=!0}if(c){(r.from!==void 0||l)&&r.rm.blit(c,{source:o,respectColorSpace:!1,transparent:!0,clear:!0});const h=1-i,u=Math.max(0,Math.min(n,h)/h);r.rm.blit(c,{source:t||gm,respectColorSpace:!1,transparent:!0,clear:!1,blendAlpha:r.from!==void 0?i:u}),s=c.texture}else s=e}return s}function rM(r,e,t,i){for(const n of Object.keys(r)){if(!t.has(n))continue;const s=e[n];if(s===void 0)continue;const a=i.from?{...i,from:i.from[n]}:i,o=r[n];if(typeof s=="number"&&typeof o=="number"){const l=Jc(a,s,o);l===s?delete r[n]:r[n]=l}if(s?.isColor&&o?.isColor){const l=Om(a,s,o);l.getHex()===s.getHex()?delete r[n]:r[n]=l}if((s==null||s.isTexture)&&(o==null||o.isTexture)&&(s||o)){const l=sM(a,s||null,o||null);l===s?delete r[n]:r[n]=l}if(s?.toArray&&o?.toArray&&s.clone&&s.fromArray&&s.equals){const l=o0(a,s,o);l.equals(s)?delete r[n]:r[n]=l}if(Array.isArray(s)&&Array.isArray(o)&&s.length===o.length){const l=s.map((c,h)=>Om(a,c,o[h]));l.every((c,h)=>c===s[h])?delete r[n]:r[n]=l}}}function aM(r,e){return r.multiplyScalar(r.w*e),r.w=1,r}function DN(r,e){return aM(r,e),new se(r.x,r.y,r.z)}function oM(r,e){const t=Math.max(r.x,Math.max(r.y,r.z));let i=Math.max(Math.min(t/e,1),0);return i=Math.ceil(i*255)/255,r.divideScalar(i*e),r.w=i,r}function RN(r,e){return oM(new rt(r.r,r.g,r.b,1),e)}function lM(){return navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}const Y_=class Y_{static async GetClonedCanvas(e,{rect:t={x:0,y:0,width:e.width,height:e.height,assumeClientRect:!1,normalized:!1},displayPixelRatio:i=1,scale:n=1}){t={...t};const s=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");t.normalized?(t.x=Math.floor(t.x*e.width),t.y=Math.floor(t.y*e.height),t.width=Math.floor(t.width*e.width),t.height=Math.floor(t.height*e.height),t.assumeClientRect&&console.warn("CanvasSnapshot: rect.assumeClientRect is ignored when rect is normalized")):t.assumeClientRect&&(t.x=Math.floor(t.x*e.width/(i*e.clientWidth)),t.y=Math.floor(t.y*e.height/(i*e.clientHeight)),t.width=Math.floor(t.width*e.width/(i*e.clientWidth)),t.height=Math.floor(t.height*e.height/(i*e.clientHeight))),s.width=Math.floor(t.width*n*i),s.height=Math.floor(t.height*n*i);const a=s.getContext("2d");if(!a)return console.error("snapshot: cannot create context"),s;const o=e.style.background||e.parentElement?.style.background||"";if(o.includes("url")){const c=/url\("(.*)"\)/ig.exec(o)?.[1];if(c){const h=new Image;h.src=c,await new Promise((u,d)=>{h.onload=()=>u(),h.onerror=()=>d(),h.complete&&u()}),a.drawImage(h,Math.floor(h.width*t.x*i/e.width),Math.floor(h.height*t.y*i/e.height),Math.floor(h.width*t.width*i/e.width),Math.floor(h.height*t.height*i/e.height),0,0,s.width,s.height)}}else a.fillStyle=e.style.background||e.parentElement?.style.backgroundColor||"#00000000",a.fillRect(0,0,s.width,s.height);return a?.drawImage(e,Math.floor(t.x*i),Math.floor(t.y*i),Math.floor(t.width*i),Math.floor(t.height*i),0,0,s.width,s.height),this.Debug&&(document.body.appendChild(s),s.style.position="absolute",s.style.top="0",s.style.left="0",s.style.borderWidth="2px",s.style.borderColor="#ff00ff",setTimeout(()=>s.remove(),5e3)),s}static async GetDataUrl(e,{mimeType:t="image/png",quality:i,...n}){const s=lM()||n.cloneCanvas||n.rect||n.scale||n.displayPixelRatio;!s&&(n.rect||n.scale||n.displayPixelRatio)&&console.warn("CanvasSnapshot: rect, scale and displayPixelRatio are ignored when cloneCanvas is false");const a=s?await this.GetClonedCanvas(e,n):e,o=a.toDataURL(t,i);return!this.Debug&&a!==e&&a.remove(),o}static async GetImage(e,t={}){const i=await this.GetDataUrl(e,t);return new Promise((n,s)=>{const a=new Image;a.onload=()=>n(a),a.onerror=()=>s(),a.src=i})}static async GetBlob(e,t={}){const i=lM()||t.cloneCanvas||t.rect||t.scale||t.displayPixelRatio;!i&&(t.rect||t.scale||t.displayPixelRatio)&&console.warn("rect, scale and displayPixelRatio are ignored when cloneCanvas is false");const n=i?await this.GetClonedCanvas(e,t):e,s=await new Promise((a,o)=>{n.toBlob(l=>{l?a(l):o(new Error("CanvasSnapshot Failed to export blob from canvas"))},t.mimeType??"image/png",t.quality)});return!this.Debug&&n!==e&&n.remove(),s}static async GetFile(e,t="image",i={}){const n="."+(i.mimeType?.split("/")[1]?.toLowerCase()||"png"),s=t.toLowerCase().endsWith(n)?t:t+n;return i.getDataUrl?await this.GetDataUrl(e,i):new File([await this.GetBlob(e,i)],s,{type:i.mimeType??"image/png",lastModified:Mn()})}static async GetTiledFiles(e,t="image",i=2,n=2,s={}){const a=s.rect??{x:0,y:0,width:1,height:1,assumeClientRect:!1,normalized:!0},o=[];for(let l=0;l<n;l++)for(let c=0;c<i;c++){const h=s.mimeType?.split("/")[1]??"png",u=await this.GetFile(e,`${t}_${l}_${c}.${h}`,{rect:{x:a.x+l*a.width/n,y:a.y+c*a.height/i,width:a.width/n,height:a.height/i,assumeClientRect:a.assumeClientRect,normalized:a.normalized}}).catch(d=>(console.error(`CanvasSnapshot - Error exporting tiled file ${l}, ${c}`,d),null));u&&o.push(u)}return o}};Y_.Debug=!1;let md=Y_;var BN=Object.defineProperty,LN=Object.getOwnPropertyDescriptor,Fi=(r,e,t,i)=>{for(var n=i>1?void 0:i?LN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&BN(e,t,n),n};const cM={None:"","Background Color":"scene.backgroundColor","Environment Rotation":"scene.environmentRotation.y","Environment Intensity":"scene.environmentIntensity","Camera Position":"scene.mainCamera.position","Camera Rotation":"scene.mainCamera.rotation","Camera Zoom":"scene.mainCamera.zoom","Camera FOV":"scene.mainCamera.fov","Tonemap Exposure":"plugins.Tonemap.exposure","Tonemap Saturation":"plugins.Tonemap.saturation","Tonemap Contrast":"plugins.Tonemap.contrast","Tonemap Tone Mapping":"plugins.Tonemap.toneMapping","SSR Intensity":"plugins.SSReflection.passes.ssr.passObject.intensity","SSR Boost":"plugins.SSReflection.passes.ssr.passObject.boost","Chromatic Aberration Intensity":"plugins.ChromaticAberration.intensity","Film Grain Intensity":"plugins.FilmicGrain.intensity","Vignette Color":"plugins.Vignette.color","Vignette Power":"plugins.Vignette.power","Depth of Field Focal Point":"plugins.DepthOfField._focalPointHit","Depth of Field Near Far Blur Scale X":"plugins.DepthOfField.pass.nearFarBlurScale.x","Depth of Field Near Far Blur Scale Y":"plugins.DepthOfField.pass.nearFarBlurScale.y","Depth of Field Focal Depth Range Y":"plugins.DepthOfField.pass.focalDepthRange.y","Bloom Intensity":"plugins.Bloom.pass.intensity","Bloom Radius":"plugins.Bloom.pass.radius","Bloom Power":"plugins.Bloom.pass.power"};function l0(r,e){let t=Array.from((r.access??"").split(new RegExp("(?<!\\\\)\\."))),i=r.targetObject,n;const s=t.pop()?.replace(/\\\./g,".");if(!s||s.length===0)return{key:void 0,tar:i};e=e??i?._animGetters;const a=t.length>=1?t[0]:void 0,o=t.length>=2?t[1]?.replace(/\\\./g,"."):void 0;if(e&&a&&a in e&&o){t=t.slice(2);const l=e[a](o,t);l?(i=l.tar,t=l.acc,n=l.onChange??n):i=l}return i=Gu(t,i),{key:s,tar:i,onChange:n}}f.AnimationObject=class extends wi{constructor(e,t,i=""){super(),this.uuid=Ui(),this.setDirty=()=>{this.updater=[],this.options&&(this.options.repeatType=this.repeatType,this.options.repeat=this.repeat),this._upfn&&(this.updateScene&&this.updater.push(this._upfn.scene),this.updateCamera&&this.updater.push(this._upfn.camera),this.updateViewer&&this.updater.push(this._upfn.viewer),this.updateTarget&&this.updater.push(this._upfn.target),this.dispatchEvent({type:"update"}))},this.name="",this.access="",this.values=[],this.offsets=[],this.options={},this.duration=1e3,this.delay=0,this.repeat=0,this.repeatDelay=0,this.repeatType="reverse",this.ease="easeInOutSine",this.updater=[],this.updateScene=!1,this.updateCamera=!1,this.updateViewer=!1,this.updateTarget=!1,this._lastAccess="",this._lastTarget=void 0,this._upfn={viewer:()=>this.getViewer()?.setDirty(),renderer:()=>this.getViewer()?.renderManager.reset(),scene:()=>{this.getViewer()?.scene.setDirty()},camera:()=>this.getViewer()?.scene.mainCamera.setDirty(),target:()=>{const n=this.targetObject;n&&typeof n.setDirty=="function"&&n.setDirty({frameFade:!1,refreshScene:!1,source:"AnimationObject",key:this.access})}},this.animSetParallel=!1,this.animSet=[],this.uiConfig={type:"folder",label:()=>this.name||this.access||"Animation",children:[()=>this.target?null:{type:"input",label:"Property",property:[this,"access"],children:Object.entries(cM).map(([n,s])=>({label:n,value:s}))},()=>this.values.flatMap((n,s)=>[{...ti(this.values,s+"",void 0,n),label:s===0?"From":s===this.values.length-1?"To":"Key "+s,onChange:()=>this.setDirty()},s>0&&s<this.values.length-1?{type:"number",label:"Offset "+s,property:[this.offsets,s+""],bounds:[0,1],onChange:()=>this.setDirty()}:null]),vi(this)],uuid:Ui()},this.target=e,this.viewer=t,this.name=i,this.dispatchEvent=this.dispatchEvent.bind(this)}get targetObject(){return it(this.target)??this.parent?.targetObject}getViewer(){return this.viewer?it(this.viewer):this.parent?.getViewer()}fromJSON(e,t){let i={...e};return i.access!==void 0&&(this.access=i.access,delete i.access),i.from!==void 0&&(i={...i},i.values=[i.from,i.to],i.offsets=[0,1],delete i.from,delete i.to),ke.Deserialize(i,this,t,!0),this.animSet.map(n=>{n.parent=this}),this}_onAccessChanged(){const e=this.targetObject;if(e&&e===this.getViewer()&&!Object.values(cM).includes(this.access)){this.access="";return}if(e&&e===this.getViewer()&&this.access==="scene.environment.rotation"){this.access="scene.environmentRotation.y";return}if(e&&e===this.getViewer()&&this.access==="scene.envMapIntensity"){this.access="scene.environmentIntensity";return}if(this.access!==this._lastAccess||!this.values.length||this._lastTarget!==e&&e&&this._lastTarget){this._lastAccess=this.access;const t=this.values;this.values=[],this.offsets=[];const i=this._thisValueCloner();if(!i){this.refreshUi();return}this.values=[i(),i()],t.length>=2&&typeof t[0]==typeof this.values[0]&&(typeof t[0]!="object"||t[0].type&&t[0].type===this.values[0]?.type)&&(this.values=t),this.offsets=this.offsets.length===this.values.length?this.offsets:[0,1],this.refreshUi()}}_thisValueCloner(){const{key:e,tar:t}=l0(this),i=t&&e!==void 0?t[e]:null;return i==null?null:()=>i&&(i.isColor?"#"+i.getHexString():typeof i.clone=="function"?i.clone():typeof i=="object"?{...i}:i)}addKeyframe(e){if(this.values.length<2){console.warn("AnimationObject: Values not initialized, cannot add keyframe",this);return}const t=this._thisValueCloner();if(!t){console.warn("AnimationObject: No value to add keyframe for",this);return}const i=e-this.delay,n=this.duration,s=this.delay,a=[...this.offsets],o=[...this.values];let l=i/this.duration,c,h=n,u=s;const d=[...this.values],p=[...this.offsets];if(l<0){const y=-l;l=0;for(let _=0;_<a.length;_++)p[_]=(a[_]+y)/(1+y);h=n-i,u=s+i,c=0}else if(l>1){const y=l-1;l=1;for(let _=0;_<a.length;_++)p[_]=a[_]/(1+y);h=i,c=a.length}else if(c=a.findIndex(y=>y>=l),c<0)c=this.offsets.length;else if(this.offsets[c]===l){console.warn("AnimationObject: Keyframe already exists at offset",l,this);return}const m=t();d.splice(c,0,m),p.splice(c,0,l);const A=()=>{this.duration=h,this.delay=u,this.values=d,this.offsets=p,this.setDirty()},g=()=>{this.duration=n,this.delay=s,this.values=o,this.offsets=a,this.setDirty()};return A(),{undo:g,redo:A}}updateKeyframe(e){if(e<0||e>=this.values.length){console.warn("AnimationObject: Invalid keyframe index",e,this);return}const t=this._thisValueCloner();if(!t){console.warn("AnimationObject: No value to update keyframe for",this);return}const i=this.values[e],n=t(),s=()=>{this.values[e]=n,this.setDirty()},a=()=>{this.values[e]=i,this.setDirty()};return s(),{undo:a,redo:s}}isValueSame(e){if(e<0||e>=this.values.length)return console.warn("AnimationObject: Invalid keyframe index",e,this),!1;const t=this._thisValueCloner();if(!t)return console.warn("AnimationObject: No value to update keyframe for",this),!1;const i=this.values[e],n=t();if(i===n)return!0;if(typeof i!=typeof n)return!1;if(typeof i=="object"&&typeof n=="object"){if(i?.equals)return i.equals(n);if(n?.equals)return n.equals(i)}return!1}refreshUi(){this.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}add(e){this.animSet.push(e),e.parent=this,this.dispatchEvent({type:"animationAdd",animation:e}),e.addEventListener("update",this.dispatchEvent),e.addEventListener("animationAdd",this.dispatchEvent),e.addEventListener("animationRemove",this.dispatchEvent),this.refreshUi()}remove(e,t=!1){const i=this.animSet.indexOf(e);i>=0&&(this.animSet.splice(i,1),e.parent=void 0,this.dispatchEvent({type:"animationRemove",animation:e,fromChild:t}),e.removeEventListener("update",this.dispatchEvent),e.removeEventListener("animationAdd",this.dispatchEvent),e.removeEventListener("animationRemove",this.dispatchEvent),this.refreshUi())}animate(e=0,t=!0){(typeof e!="number"||isNaN(e))&&(e=0),t&&this.result&&(console.warn("AnimationObject: Already animating, stopping previous animation"),this.stop());const i=this.getViewer(),n=i?.getPlugin("PopmotionPlugin");if(!n){console.error(`AnimationObject: No ${i?"PopmotionPlugin":"viewer"}`);const s=Ui();return{id:s,options:this.options,stop:()=>{},promise:Promise.resolve(s),anims:[]}}return n.animateObject(this,0,t,void 0,e)}stop(){this.result&&(this.result.stop(),this.result=void 0)}async removeFromParent2(){const e=this.getViewer();this.parent&&e&&await e.dialog.confirm(`Delete: Are you sure you want to delete the animation ${this.name}?`)&&this.removeFromParent()}removeFromParent(){this.parent&&this.parent.remove(this,!0)}addAnimation(){const e=new f.AnimationObject(this.target);return this.add(e),e}},Fi([z(),de("setDirty")],f.AnimationObject.prototype,"name",2),Fi([z(),de(f.AnimationObject.prototype._onAccessChanged)],f.AnimationObject.prototype,"access",2),Fi([z()],f.AnimationObject.prototype,"values",2),Fi([z()],f.AnimationObject.prototype,"offsets",2),Fi([z()],f.AnimationObject.prototype,"options",2),Fi([z(),Oe(void 0,[0,1e4],1,r=>({hidden:()=>!r.access})),de("setDirty")],f.AnimationObject.prototype,"duration",2),Fi([z(),Oe(void 0,[0,1e4],1,r=>({hidden:()=>!r.access})),de("setDirty")],f.AnimationObject.prototype,"delay",2),Fi([z(),de("setDirty")],f.AnimationObject.prototype,"repeat",2),Fi([z(),de("setDirty")],f.AnimationObject.prototype,"repeatDelay",2),Fi([z(),de("setDirty")],f.AnimationObject.prototype,"repeatType",2),Fi([z(),Oi("ease",Object.keys(Kc).map(r=>({label:r})),r=>({hidden:()=>!r.access})),de("setDirty")],f.AnimationObject.prototype,"ease",2),Fi([z(),ae(void 0,r=>({hidden:()=>!r.access})),de("setDirty")],f.AnimationObject.prototype,"updateScene",2),Fi([z(),ae(void 0,r=>({hidden:()=>!r.access})),de("setDirty")],f.AnimationObject.prototype,"updateCamera",2),Fi([z(),ae(void 0,r=>({hidden:()=>!r.access})),de("setDirty")],f.AnimationObject.prototype,"updateViewer",2),Fi([z(),de("setDirty")],f.AnimationObject.prototype,"updateTarget",2),Fi([de(f.AnimationObject.prototype._onAccessChanged)],f.AnimationObject.prototype,"target",2),Fi([de(f.AnimationObject.prototype._onAccessChanged)],f.AnimationObject.prototype,"viewer",2),Fi([lt("Animate")],f.AnimationObject.prototype,"animate",1),Fi([lt("Stop")],f.AnimationObject.prototype,"stop",1),Fi([lt("Delete")],f.AnimationObject.prototype,"removeFromParent2",1),Fi([z()],f.AnimationObject.prototype,"animSetParallel",2),Fi([z()],f.AnimationObject.prototype,"animSet",2),f.AnimationObject=Fi([Vc("AnimationObject")],f.AnimationObject);function hM(r){return{processObject:e=>{const t=it(r);if(!(!t||e.userData.autoRegisterInManager===!1)&&(t.object3dManager.registerObject(e),e.material)){if(!t.assetManager){console.error("AssetManager is not initialized yet, cannot register material",e.material);return}const i=Array.isArray(e.material)?e.material:[e.material];for(const n of i)n.userData.autoRegisterInManager!==!1&&t.assetManager.materials.registerMaterial(n)}}}}function uM(r,{autoCenter:e=!1,centerGeometries:t=!1,centerGeometriesKeepPosition:i=!0,autoScale:n=!1,autoScaleRadius:s=2,license:a}){a&&(r.userData.license=[r.userData.license,a].filter(l=>l).join(", "));const o=()=>{e&&!r.userData.isCentered&&!r.userData.pseudoCentered&&!r.isLight?r.autoCenter&&r.autoCenter():r.userData.isCentered=!0,n&&!r.userData.autoScaled&&!r.isLight?r.autoScale&&r.autoScale(r.userData.autoScaleRadius||s):r.userData.autoScaled=!0,t&&!r.userData.geometriesCentered&&c0(r,i),r.userData.geometriesCentered=!0};r._loadingPromise?r._loadingPromise.finally(o):o()}function c0(r,e){const t=new Set;r.traverseModels&&r.traverseModels(n=>{n.geometry&&t.add(n.geometry)},{visible:!1,widgets:!1});const i=[];return t.forEach(n=>i.push(n.center2(void 0,e))),()=>i.forEach(n=>n())}class ON extends Zt{constructor(e){super(e),this.responseType="blob"}load(e,t,i,n){return super.load(e,s=>{try{t?.(qp(s))}catch(a){n?.(a)}},i,n)}}var UN=Object.defineProperty,FN=Object.getOwnPropertyDescriptor,Ni=(r,e,t,i)=>{for(var n=i>1?void 0:i?FN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&UN(e,t,n),n};const Qi=r=>({onChange:e=>{e.last&&r.onChange()}});f.TextSVGOptions=class{constructor(){this.text="Custom Text",this.fontSize=100,this.width=1024,this.height=1024,this.xOffset=0,this.yOffset=0,this.boxWidth=1024,this.boxHeight=1024,this.textAnchor="middle",this.fontFamily="",this.fontPath="",this.fontWeight="normal",this.fontStyle="normal",this.lineHeight="normal",this.letterSpacing="normal",this.whiteSpace="normal",this.direction="ltr",this.maskText=!1,this.innerShadow=!1,this.textColor="#000000",this.bgFillColor="#ffffff",this.svgBackground="#ffffff",this.onChange=()=>{}}set(e){Object.assign(this,e)}reset(){const e=this.onChange;Object.assign(this,new f.TextSVGOptions),this.onChange=e}toJSON(){return{text:this.text,fontFamily:this.fontFamily,fontPath:this.fontPath,svgBackground:this.svgBackground,width:this.width,height:this.height,xOffset:this.xOffset,yOffset:this.yOffset,boxWidth:this.boxWidth,boxHeight:this.boxHeight,fontSize:this.fontSize,fontWeight:this.fontWeight,fontStyle:this.fontStyle,lineHeight:this.lineHeight,letterSpacing:this.letterSpacing,whiteSpace:this.whiteSpace,direction:this.direction,maskText:this.maskText,innerShadow:this.innerShadow,bgFillColor:this.bgFillColor,textColor:this.textColor,textAnchor:this.textAnchor}}},Ni([Fe("Text",Qi)],f.TextSVGOptions.prototype,"text",2),Ni([Oe("Font Size",[2,1024],1,Qi)],f.TextSVGOptions.prototype,"fontSize",2),Ni([Oe("Width",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"width",2),Ni([Oe("Height",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"height",2),Ni([Oe("X Offset",[-1024,1024],1,Qi)],f.TextSVGOptions.prototype,"xOffset",2),Ni([Oe("Y Offset",[-1024,1024],1,Qi)],f.TextSVGOptions.prototype,"yOffset",2),Ni([Oe("V-Width",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"boxWidth",2),Ni([Oe("V-Height",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"boxHeight",2),Ni([Oi("Text Anchor",["start","middle","end"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"textAnchor",2),Ni([Fe("Font",Qi)],f.TextSVGOptions.prototype,"fontFamily",2),Ni([Fe("Font Url",Qi)],f.TextSVGOptions.prototype,"fontPath",2),Ni([Fe("Font Weight",Qi)],f.TextSVGOptions.prototype,"fontWeight",2),Ni([Oi("Font Style",["normal","italic","oblique"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"fontStyle",2),Ni([Fe("Line Height",Qi)],f.TextSVGOptions.prototype,"lineHeight",2),Ni([Fe("Letter Spacing",Qi)],f.TextSVGOptions.prototype,"letterSpacing",2),Ni([Oi("White Space",["normal","pre","nowrap","pre-wrap","pre-line"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"whiteSpace",2),Ni([Oi("Direction",["auto","ltr","rtl"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"direction",2),Ni([ae("Mask Text",Qi)],f.TextSVGOptions.prototype,"maskText",2),Ni([ae("Inner Shadow",Qi)],f.TextSVGOptions.prototype,"innerShadow",2),Ni([Fe("Text Color",Qi)],f.TextSVGOptions.prototype,"textColor",2),Ni([Fe("BG Fill",Qi)],f.TextSVGOptions.prototype,"bgFillColor",2),Ni([Fe("SVG BG",Qi)],f.TextSVGOptions.prototype,"svgBackground",2),f.TextSVGOptions=Ni([gt("Text SVG Options")],f.TextSVGOptions);const dM={woff:"woff",woff2:"woff2",ttf:"truetype",otf:"opentype",eot:"embedded-opentype"};function fM({text:r="Custom Text",svgBackground:e="#ffffff",xOffset:t=0,yOffset:i=0,width:n=1024,height:s=1024,boxWidth:a=1024,boxHeight:o=1024,fontFamily:l="",fontSize:c=32,fontWeight:h="normal",fontStyle:u="normal",lineHeight:d="normal",letterSpacing:p="normal",whiteSpace:m="normal",direction:A="auto",maskText:g=!1,innerShadow:y=!1,bgFillColor:_="#000000",textColor:v="#ffffff",textAnchor:b="middle",style:T=""}){return`
<svg style="background-color:${e}" width="${n}" height="${s}" viewBox="0 0 ${a} ${o}"
 xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
     <defs>
        <style>
        ${T}
        .text-g{
            overflow:hidden; text-anchor: ${b}; 
            font-size: ${c}px;
            font-family: ${JSON.stringify(l||"Arial")};
            font-weight: ${h};
            font-style: ${u};
            line-height: ${d};
            letter-spacing: ${p};
            white-space: ${m};
            direction: ${A};
        }
        </style>
    </defs>

    <g class="text-g">
        <defs>

`+(g?`
<mask id="textMask">
<text style="fill:white; font-size: ${c}px; font-weight: ${h}; font-style: ${u}; line-height: ${d}; letter-spacing: ${p}; white-space: ${m}; direction: ${A};" x="${t+a/2}" y="${o/2+i+c/4}" > ${r} </text>
</mask>
`:"")+`

`+(y?`
<filter id="innerShadow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur in="SourceGraphic" stdDeviation="0.5" result="blur"/>
<feOffset in="blur" dx="1.5" dy="1.5"/>
</filter>
`:"")+`

        </defs>

`+(g?`
        <g mask="url(#textMask)">
`:"")+`

        <rect x="0" y="0" width="${a}" height="${o}" style="fill:${_}"/>
        <text style="${y?"filter: url(#innerShadow);":""} fill:${v}; font-weight: ${h}; font-style: ${u}; line-height: ${d}; letter-spacing: ${p}; white-space: ${m}; direction: ${A};" x="${t+a/2}" y="${o/2+i+c/4}"> ${r} </text>

`+(g?`
        </g>
`:"")+`

    </g>
</svg>
`}const NN={roboto:"https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2"};async function kN(r,e){const t=r.fontFamily||"Arial";let i=r.fontPath||NN[t]||"",n=r.style||"";if(i.length>0){!Hc(i)&&!i.startsWith("blob:")&&!i.startsWith("ftp:")&&globalThis.window&&(i=new URL(i,window.location.href).href);const o=Fu(i)||"woff";n+=`
`+(i.length>0?`
            @font-face {
                font-family: ${JSON.stringify(t)};
                src: url(${i}) format(${dM[o]||o});
            }`:"")}let s=fM({...r,fontFamily:t,style:n});s=await cS(s,async o=>GN(o,e)),s=jy(s);const a=await e.importSingle(s);return a?(a.generateMipmaps=!1,a.minFilter=st,a.flipY=!0,a.needsUpdate=!0,a):null}async function GN(r,e){if(r.startsWith("http://www.w3.org"))return r;if(!e)throw new Error("no importer");const t={fileHandler:new ON(e.loadingManager),processRaw:!1};try{return await e.importSingle(r,t)}catch(i){return console.error(i),""}}const $_=class $_ extends wi{constructor(){super(...arguments),this._dirty=!1,this.uiConfig=void 0,this._viewerListeners={},this._onViewerEvent=e=>{const t=e.eType;return t&&this._viewerListeners[t]?.(e),e},this._disabledBy=new Set,this.disable=(e,t=!0)=>{const i=this._disabledBy.size;this._disabledBy.add(e),t&&this.setDirty&&i!==this._disabledBy.size&&this.setDirty()},this.enable=(e,t=!0)=>{const i=this._disabledBy.size;this._disabledBy.delete(e),t&&this.setDirty&&i!==this._disabledBy.size&&this.setDirty()},this.isDisabled=()=>this._disabledBy.size>0||!this.enabled}dispose(){}toJSON(e){const t=ke.Serialize(this,e,!0);return t.type=this.constructor.PluginType,t.assetType="config",this.dispatchEvent({type:"serialize",data:t}),t}fromJSON(e,t){return e.type!==this.constructor.PluginType&&e.type!==this.constructor.OldPluginType?null:(ke.Deserialize(e,this,t,!0),this.dispatchEvent({type:"deserialize",data:e,meta:t}),this)}_storeKey(e){return(e??"webgi")+"_"+(this.constructor.PluginType||this.constructor.name)}exportState(){return this._viewer?.exportPluginConfig(this)??this.toJSON?.()}async importState(e){this._viewer?await this._viewer.importPluginConfig(e,this):this.fromJSON?.(e)}get dirty(){return this.enabled&&this._dirty}set dirty(e){this._dirty=e}};$_.PluginType="AViewerPlugin";let Zc=$_;class pt extends Zc{constructor(){super(...arguments),this.isViewerPluginSync=!0}onAdded(e){this._viewer=e,this._viewer.addEventListener("*",this._onViewerEvent)}onRemove(e){this._viewer!==e&&e.console.error("Wrong viewer"),this._viewer?.removeEventListener("*",this._onViewerEvent),this._viewer=void 0}}class zN extends Zc{constructor(){super(...arguments),this.isViewerPluginSync=!1}async onAdded(e){this._viewer=e,this._viewer.addEventListener("*",this._onViewerEvent)}async onRemove(e){this._viewer!==e&&e.console.error("Wrong viewer"),this._viewer?.removeEventListener("*",this._onViewerEvent),this._viewer=void 0}}function Um(){return[{type:"checkbox",label:"Auto LookAt Target",getValue:()=>this.userData.autoLookAtTarget??!1,setValue:r=>{this.userData.autoLookAtTarget=r,this.uiConfig?.uiRefresh?.(!0,"postFrame")}},{type:"input",label:"Auto Near Far",property:[this,"autoNearFar"]},{type:"number",label:"Min Near",hidden:()=>!this.autoNearFar,getValue:()=>this.userData.minNearPlane??ct.defaultMinNear,setValue:r=>{r===ct.defaultMinNear?delete this.userData.minNearPlane:this.userData.minNearPlane=r}},{type:"number",label:"Max Far",hidden:()=>!this.autoNearFar,getValue:()=>this.userData.maxFarPlane??ct.defaultMaxFar,setValue:r=>{r===ct.defaultMaxFar?delete this.userData.maxFarPlane:this.userData.maxFarPlane=r}},{type:"number",label:"Near",readOnly:()=>this.autoNearFar,property:[this,"near"]},{type:"number",label:"Far",readOnly:()=>this.autoNearFar,property:[this,"far"]},()=>({type:"dropdown",label:"Controls Mode",property:[this,"controlsMode"],children:["","orbit",...this.controlsCtors.keys()].map(r=>({label:r===""?"none":r,value:r})),onChange:()=>this.refreshCameraControls()}),{type:"button",label:"Set View",tags:["context-menu"],value:()=>{this.setViewToMain({ui:!0}),this.uiConfig?.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Activate main",hidden:()=>this?.isMainCamera,tags:["context-menu"],value:()=>{this.activateMain({ui:!0}),this.uiConfig?.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Deactivate main",tags:["context-menu"],hidden:()=>!this?.isMainCamera,value:()=>{this.deactivateMain({ui:!0}),this.uiConfig?.uiRefresh?.(!0,"postFrame")}}]}function pM(r){if(!this)return{};if(this.uiConfig)return this.uiConfig;const e={type:"folder",label:()=>this.name||"unnamed",expanded:!0,onChange:t=>{if(!t.config||t.config.onChange)return;let i=Array.isArray(t.config.property)?t.config.property[1]:t.config.property;i=typeof i=="string"?i:void 0,this.setDirty&&this.setDirty({uiChangeEvent:t,refreshScene:!1,refreshUi:!!t.last,change:i})},children:[{type:"checkbox",label:"Visible",property:[this,"visible"],onChange:t=>{this.setDirty?.({uiChangeEvent:t,refreshScene:!0,refreshUi:!0,change:"visible"})}},{type:"input",property:[this,"uuid"],disabled:!0,tags:["advanced"]},{type:"input",label:"Name",property:[this,"name"],onChange:t=>{t.last&&this.setDirty?.({uiChangeEvent:t,refreshScene:!0,frameFade:!1,refreshUi:!0,change:"name"})}},{type:"checkbox",label:"Casts Shadow",hidden:()=>!this.isMesh,property:[this,"castShadow"],onChange:t=>{this.setDirty?.({uiChangeEvent:t,refreshScene:!0,refreshUi:!0,change:"castShadow"})}},{type:"checkbox",label:"Receive Shadow",hidden:()=>!this.isMesh,property:[this,"receiveShadow"],onChange:t=>{this.setDirty?.({uiChangeEvent:t,refreshScene:!0,refreshUi:!0,change:"receiveShadow"})}},{type:"checkbox",label:"Frustum culled",property:[this,"frustumCulled"]},{type:"vec3",label:"Position",property:[this,"position"]},{type:"vec3",label:"Rotation",property:[this,"rotation"]},{type:"vec3",label:"Scale",property:[this,"scale"]},{type:"input",label:"Render Order",property:[this,"renderOrder"]},{type:"button",label:"Scale to Radius",tags:["context-menu","interaction"],hidden:()=>!this.autoScale,value:async()=>{const t=(this.userData.autoScaleRadius||2)+"",i=await f.ThreeViewer.Dialog.prompt("Auto Scale Radius: Object will be scaled to the given radius",t);if(i===null)return;const n=parseFloat(i||t);if(Math.abs(n)>0)return{action:()=>this.autoScale?.(n),undo:()=>this.autoScale?.(n,void 0,void 0,!0)}}},{type:"button",label:"Auto Center",tags:["context-menu","interaction"],hidden:()=>!this.autoCenter,value:()=>({action:()=>this.autoCenter?.(!0),undo:()=>this.autoCenter?.(!0,!0)})},{type:"button",label:"Pivot to Node Center",tags:["context-menu","interaction"],value:async()=>{if(await f.ThreeViewer.Dialog.confirm("Pivot to Center: Adjust the pivot to bounding box center. The object will rotate around the new pivot, are you sure you want to proceed?"))return this.pivotToBoundsCenter?.(!0)}},...uo.call(this),{type:"folder",label:"Rotate model",children:["X +","X -","Y +","Y -","Z +","Z -"].map(t=>({type:"button",label:"Rotate "+t+"90",value:()=>{const i=new x(t.includes("X")?1:0,t.includes("Y")?1:0,t.includes("Z")?1:0),n=Math.PI/2*(t.includes("-")?-1:1);return{action:()=>{this.rotateOnAxis(i,n),this.setDirty?.({refreshScene:!0,refreshUi:!1})},undo:()=>{this.rotateOnAxis(i,-n),this.setDirty?.({refreshScene:!0,refreshUi:!1})}}}}))},this.userData.license!==void 0?{type:"input",label:"License/Credits",property:[this.userData,"license"]}:{}]};if((this.isLine||this.isMesh)&&r!==!1){const t=[()=>{const i=Object.entries(this.morphTargetDictionary||{});return i.length?{label:"Morph Targets",type:"folder",children:i.map(([n,s])=>({type:"slider",label:n,bounds:[0,1],stepSize:1e-4,property:[this.morphTargetInfluences,s],onChange:a=>{this.setDirty?.({refreshScene:a.last,frameFade:!1,refreshUi:!1})}}))}:void 0},{type:"divider"}];e.children.push(...t)}if(this.isCamera){const t=Um.call(this);e.children.push(...t)}return e.children.push(Fm.call(this)),this.uiConfig=e,e}function Fm(){return r=>this.objectExtensions?.flatMap(e=>(e.uuid=e.uuid||Ui(),this.__objExtUiConfigs=this.__objExtUiConfigs||{},this.__objExtUiConfigs[e.uuid]||(this.__objExtUiConfigs[e.uuid]=e.getUiConfig?e.getUiConfig(this,this.uiConfig?.uiRefresh):void 0),this.__objExtUiConfigs[e.uuid]?.flatMap(t=>it(t,r)))).filter(e=>e)}function Nm(r,e,t){t=t??r.name;const i=t.match(/\(copy( (\d+))?\)$/);if(i){let n=i[2]?parseInt(i[2])+1:2,s=t.replace(/\(copy( \d+)?\)$/,`(copy ${n})`);const a=r.parent;if(a&&a!==e.parent){const o=new Set(a.children.filter(l=>l!==r).map(l=>l.name));for(let l=0;l<1e3&&o.has(s);l++)n++,s=t.replace(/\(copy( \d+)?\)$/,`(copy ${n})`)}e.name=s}else e.name=t+" (copy)"}function uo(){return[{type:"button",label:"Duplicate Object",tags:["context-menu"],value:async r=>Ge.duplicateObject(this,r)},{type:"button",label:"Delete Object",tags:["context-menu"],value:async r=>Ge.deleteObject(this,r)}]}const ri={setDirty:function(r){this.dispatchEvent({bubbleToObject:!0,...r,type:"geometryUpdate",geometry:this}),this.refreshUi()},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},dispose:r=>function(e=!0){!e&&this.userData.disposeOnIdle===!1||r.call(this)},clone:r=>function(){return ri.upgradeGeometry.call(r.call(this))},upgradeGeometry:VN,center:r=>function(e,t=!1,i=!0){if(t){e=e?e.clone():new x,r.call(this,e),e.negate();const n=this.appliedMeshes;for(const s of n)s.updateMatrix(),s.position.copy(e).applyMatrix4(s.matrix),i&&s.setDirty&&s.setDirty()}else r.call(this,e);return i&&this.setDirty(),this},center2:function(r,e=!1,t=!0){const i=r||new x;if(e){this.center(i,!1,!1);const n=this.appliedMeshes,s=new WeakMap;for(const a of n)a.updateMatrix(),s.set(a,a.position.clone()),a.position.set(-i.x,-i.y,-i.z).applyMatrix4(a.matrix),t&&a.setDirty&&a.setDirty();return t&&this.setDirty&&this.setDirty(),()=>{for(const a of n){const o=s.get(a);if(!o){console.warn("GeometryCommons: No position found for mesh",a);continue}a.position.copy(o),t&&a.setDirty&&a.setDirty()}t&&this.setDirty&&this.setDirty()}}else return this.center(i,!1,!1),t&&this.setDirty&&this.setDirty(),()=>{this.translate(-i.x,-i.y,-i.z),t&&this.setDirty&&this.setDirty()}},makeUiConfig:function(){return this.uiConfig?this.uiConfig:{label:"Geometry",uuid:"geom",type:"folder",children:[{type:"input",property:[this,"name"]},{type:"input",property:[this,"uuid"],disabled:!0,tags:["advanced"]},()=>this.groups.length?{type:"folder",label:"Groups",uuid:"groups",tags:["advanced"],children:this.groups.map((r,e)=>({type:"folder",label:`Group ${e}`,uuid:"group-"+e,tags:["advanced"],children:[{type:"input",label:"Start",uuid:"start",getValue:()=>r.start,setValue:t=>{r.start=t,this.setDirty&&this.setDirty()}},{type:"input",label:"Count",uuid:"count",getValue:()=>r.count,setValue:t=>{r.count=t,this.setDirty&&this.setDirty()}},{type:"input",label:"Material Index",uuid:"mi",getValue:()=>r.materialIndex,setValue:t=>{r.materialIndex=t,this.setDirty&&this.setDirty()}}]}))}:null,{type:"divider"},{type:"button",label:"Center Geometry",tags:["context-menu"],value:async()=>{if(await f.ThreeViewer.Dialog.confirm("This will move the objects based on the geometry center, do you want to continue?"))return this.center2()}},{type:"button",label:"Center Geometry (keep position)",tags:["context-menu"],value:async()=>{if(await f.ThreeViewer.Dialog.confirm("This will move the geometry center keeping the object position, do you want to continue?"))return this.center2(void 0,!0)}},{type:"button",label:"Compute vertex normals",tags:["context-menu"],value:async()=>{this.hasAttribute("normal")&&!await f.ThreeViewer.Dialog.confirm(`Normals already exist, replace with computed normals?
This action cannot be undone.`)||(this.computeVertexNormals(),this.setDirty&&this.setDirty())}},{type:"button",label:"Compute vertex tangents",tags:["context-menu"],value:async()=>{this.hasAttribute("tangent")&&!await f.ThreeViewer.Dialog.confirm(`Tangents already exist, replace with computed tangents?
This action cannot be undone.`)||(this.computeTangents(),this.setDirty&&this.setDirty())}},{type:"button",label:"Normalize normals",tags:["context-menu"],value:()=>{this.normalizeNormals(),this.setDirty&&this.setDirty()}},{type:"button",label:"Convert to indexed",hidden:()=>!!this.index,tags:["context-menu"],value:async()=>{if(this.attributes.index)return;const r=parseFloat(await f.ThreeViewer.Dialog.prompt("Convert to Indexed: Tolerance?","-1")??"-1");Cv(this,r),this.setDirty&&this.setDirty()}},{type:"button",label:"Convert to non-indexed",hidden:()=>!this.index,tags:["context-menu"],value:()=>{this.attributes.index&&(this.toNonIndexed(),this.setDirty&&this.setDirty())}},{type:"button",label:"Create uv1 from uv",tags:["context-menu"],value:async()=>{this.hasAttribute("uv1")&&!await f.ThreeViewer.Dialog.confirm(`uv1 already exists, replace with uv data?
This action cannot be undone.`)||(this.setAttribute("uv1",this.getAttribute("uv")),this.setDirty&&this.setDirty())}},{type:"button",label:"Remove vertex color attribute",hidden:()=>!this.hasAttribute("color"),tags:["context-menu"],value:async()=>{if(!this.hasAttribute("color")){await f.ThreeViewer.Dialog.alert("No color attribute found");return}await f.ThreeViewer.Dialog.confirm("Remove color attribute?")&&(this.deleteAttribute("color"),this.setDirty&&this.setDirty())}},{type:"button",label:"Auto GPU Instances",hidden:()=>!this.appliedMeshes||this.appliedMeshes.size<2,tags:["context-menu"],value:async()=>{await f.ThreeViewer.Dialog.confirm("This will automatically create Instanced Mesh from geometry instances. This action is irreversible, do you want to continue?")&&Iv(this)}},{type:"input",label:"Mesh count",getValue:()=>this.appliedMeshes?.size??0,disabled:!0}]}}};function VN(){return this.assetType==="geometry"?this:this.isBufferGeometry?(this.assetType="geometry",this.dispose=ri.dispose(this.dispose),this.center=ri.center(this.center),this.clone=ri.clone(this.clone),this.center2||(this.center2=ri.center2),this.setDirty||(this.setDirty=ri.setDirty),this.refreshUi||(this.refreshUi=ri.refreshUi),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.uiConfig=ri.makeUiConfig.call(this),this):(console.error("Geometry is not a BufferGeometry",this),this)}const K_=class K_{static ApplyMaterialExtensions(e,t,i,n){for(const s of i)this.ApplyMaterialExtension(e,t,s,n)}static ApplyMaterialExtension(e,t,i,n){let s=it(i.parsFragmentSnippet,n,e)??"";s.length&&(t.fragmentShader=At(t.fragmentShader,this.VoidMain,`
`+s+`
`,{prepend:!0})),s=it(i.parsVertexSnippet,n,e)??"",s.length&&(t.vertexShader=At(t.vertexShader,this.VoidMain,`
`+s+`
`,{prepend:!0})),i.extraUniforms&&(t.uniforms=Object.assign(t.uniforms,eS(i.extraUniforms,a=>it(a,t)||{value:null}))),i.extraDefines&&ba(i.extraDefines,e),i.shaderExtender&&i.shaderExtender(t,e,n),e.lastShader=t}static CacheKeyForExtensions(e,t){let i="";for(const n of t)i+=this.CacheKeyForExtension(e,n);return i}static CacheKeyForExtension(e,t){let i="";return t.computeCacheKey?i+=it(t.computeCacheKey,e):i+=t.uuid,t.extraDefines&&(i+=Object.values(t.extraDefines).map(n=>it(n)??"").join("")),i}static RegisterExtensions(e,t){const i=[];if(Array.isArray(e.materialExtensions)||(e.materialExtensions=[]),t)for(const n of t)e.materialExtensions.includes(n)||n.isCompatible!==void 0&&(!n.isCompatible||!n.isCompatible(e))||(i.push(n),n.uuid||(n.uuid=Ui()),n.__setDirty||(n.__setDirty=()=>{n.updateVersion||(n.updateVersion=0),n.updateVersion++}),n.setDirty||(n.setDirty=n.__setDirty));if(!i.length)return[];e.materialExtensions=[...e.materialExtensions||[],...i].sort((n,s)=>(s.priority||0)-(n.priority||0)),e.__extListen||(e.__extListen=!0,e.addEventListener("beforeRender",mM),e.addEventListener("afterRender",gM),e.addEventListener("addToMesh",AM),e.addEventListener("removeFromMesh",yM),e.addEventListener("materialUpdate",vM));for(const n of i)n.onRegister&&n.onRegister(e);return e.needsUpdate=!0,i}static UnregisterExtensions(e,t){if(t){e.materialExtensions=e.materialExtensions?.filter(i=>!t.includes(i))||[];for(const i of t)i.onUnregister&&i.onUnregister(e)}!e.materialExtensions?.length&&e.__extListen&&(e.removeEventListener("beforeRender",mM),e.removeEventListener("afterRender",gM),e.removeEventListener("addToMesh",AM),e.removeEventListener("removeFromMesh",yM),e.removeEventListener("materialUpdate",vM),delete e.__extListen)}};Object.assign(ot,sv),K_.VoidMain="void main()";let gl=K_;function ba(r,e){if(!r||!e)return;(e.defines===void 0||e.defines===null)&&(e.defines={});let t=!1;const i=Object.entries(r);for(const[n,s]of i){const a=it(s);a===void 0?e.defines[n]!==void 0&&(delete e.defines[n],t=!0):e.defines[n]!==a&&(e.defines[n]=typeof a=="boolean"?+a:a,t=!0)}t&&(e.needsUpdate=!0)}function mM({target:r,object:e,renderer:t}){const i=r;if(!i||!e||!t)throw new Error("Invalid material, object or renderer");if(i.materialExtensions)for(const n of i.materialExtensions){if(n.onObjectRender&&n.onObjectRender(e,i,t),i.lastShader){const a=it(n.updaters)||[];for(const o of a)o&&o.updateShaderProperties(i.lastShader)}const s="_"+n.uuid+"_version";n.updateVersion!==i.userData[s]&&(i.userData[s]=n.updateVersion,i.needsUpdate=!0)}}function gM({target:r,object:e,renderer:t}){const i=r;if(!i||!e||!t)throw new Error("Invalid material, object or renderer");if(i.materialExtensions)for(const n of i.materialExtensions)n.onAfterRender&&n.onAfterRender(e,i,t)}function AM({target:r,object:e}){const t=r;if(!t||!e)throw new Error("Invalid material or object");if(t.materialExtensions)for(const i of t.materialExtensions)i.onAddToMesh&&i.onAddToMesh(e,t)}function yM({target:r,object:e}){const t=r;if(!t||!e)throw new Error("Invalid material or object");if(t.materialExtensions)for(const i of t.materialExtensions)i.onRemoveFromMesh&&i.onRemoveFromMesh(e,t)}function vM({target:r}){const e=r;if(!e)throw new Error("Invalid material");if(e.materialExtensions)for(const t of e.materialExtensions)t.onMaterialUpdate&&t.onMaterialUpdate(e)}function _M(r,e){const t=e||Ui();return{uuid:t,getUiConfig:i=>{if(i.__uiConfigs||(i.__uiConfigs={}),i.__uiConfigs[t])return i.__uiConfigs[t];const n=r(i);return i.__uiConfigs[t]=n,n},isCompatible:()=>!0}}function Ti(r,e,t,i,n){return n=n??(()=>r.setDirty&&r.setDirty()),{type:"folder",label:t??e+" Sampler",hidden:()=>!r[e]||i&&i(),onChange:n,children:[()=>({type:"vec2",label:"Repeat",stepSize:.001,property:[r[e],"repeat"]}),()=>({type:"vec2",label:"Offset",stepSize:.001,property:[r[e],"offset"]}),()=>({type:"vec2",label:"Center",stepSize:.001,property:[r[e],"center"]}),()=>({type:"input",label:"Rotation",stepSize:.001,bounds:[-Math.PI,Math.PI],property:[r[e],"rotation"]}),()=>({type:"dropdown",label:"Color space",property:[r[e],"colorSpace"],children:[["Linear",Dt],["sRGB",vt]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{const s=r[e];s&&(s.needsUpdate=!0)}]}),()=>({type:"dropdown",label:"UV Channel",property:[r[e],"channel"],children:[0,1,2,3].map(s=>({label:s.toString(),value:s})),onChange:()=>{const s=r[e];s&&(s.needsUpdate=!0)}}),()=>({type:"checkbox",label:"Flip Y",getValue:()=>r[e]?.flipY??!1,setValue:s=>{const a=r[e];if(a&&a.flipY!==s)if(a.image&&ImageBitmap&&a.image instanceof ImageBitmap){const o=a,l=a.source.data;createImageBitmap(l,{imageOrientation:"flipY"}).then(c=>{l.close&&l.close(),o.flipY=s,o.source.data=c,o.source.needsUpdate=!0,o.needsUpdate=!0,n()})}else a.flipY=s,a.needsUpdate=!0,n()}}),()=>({type:"dropdown",label:"Wrap S",property:[r[e],"wrapS"],children:[["ClampToEdge",ui],["MirroredRepeat",Zr],["Repeat",Bn]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]}),()=>({type:"dropdown",label:"Wrap T",property:[r[e],"wrapT"],children:[["ClampToEdge",ui],["MirroredRepeat",Zr],["Repeat",Bn]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]}),()=>({type:"input",label:"Anisotropy",bounds:[1,6],stepSize:1,property:[r[e],"anisotropy"],onChange:[()=>{r[e]&&(r[e].needsUpdate=!0),r.needsUpdate=!0}]}),()=>({type:"dropdown",label:"Min Filter",property:[r[e],"minFilter"],children:[["Linear",st],["Nearest",pi],["NearestMipmapNearest",Jh],["NearestMipmapLinear",Na],["LinearMipmapNearest",Po],["LinearMipmapLinear",Ln]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]}),()=>({type:"dropdown",label:"Mag Filter",property:[r[e],"magFilter"],children:[["Linear",st],["Nearest",pi]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]})]}}const qt={base:r=>[{type:"input",property:[r,"name"]},{type:"checkbox",property:[r,"wireframe"]},{type:"checkbox",property:[r,"vertexColors"]},{type:"color",property:[r,"color"]},r.flatShading!==void 0?{type:"checkbox",property:[r,"flatShading"]}:{},{type:"image",property:[r,"map"]},Ti(r,"map")],blending:r=>({type:"folder",label:"Blending",children:[{type:"slider",bounds:[0,1],property:[r,"opacity"]},{type:"checkbox",property:[r,"transparent"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"transparent"})},{type:"dropdown",property:[r,"depthFunc"],children:[["Never",Sb],["Always",Eb],["Less",Mb],["LessEqual",ql],["Equal",Tb],["GreaterEqual",Ib],["Greater",Pb],["NotEqual",Db]].map(e=>({label:e[0],value:e[1]}))},{type:"checkbox",property:[r,"depthTest"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"depthTest"})},{type:"checkbox",property:[r,"depthWrite"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"depthWrite"})},{type:"checkbox",property:[r,"colorWrite"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"colorWrite"})},{type:"slider",bounds:[0,1],stepSize:.001,property:[r,"alphaTest"]},{type:"checkbox",property:[r,"alphaHash"]},{type:"checkbox",property:[r,"dithering"]},{type:"dropdown",label:"Blending",property:[r,"blending"],children:[["None",gn],["Normal",xr],["Additive",rf],["Subtractive",af],["Multiply",of],["Custom",ir]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",hidden:()=>r.blending!==ir,property:[r,"blendingEquation"],children:[["Add",Sr],["Subtract",_b],["Reverse Subtract",bb],["Min",wb],["Max",Cb]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",property:[r,"blendSrc"],hidden:()=>r.blending!==ir,children:[["Zero",Jg],["One",Zg],["Src Color",eA],["One Minus Src Color",tA],["Src Alpha",Hl],["One Minus Src Alpha",Ql],["Dst Alpha",iA],["One Minus Dst Alpha",nA],["Dst Color",sA],["One Minus Dst Color",rA],["Src Alpha Saturate",xb],["Constant Color",Yh],["One Minus Constant Color",$h],["Constant Alpha",jl],["One Minus Constant Alpha",Wl]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",property:[r,"blendDst"],hidden:()=>r.blending!==ir,children:[["Zero",Jg],["One",Zg],["Src Color",eA],["One Minus Src Color",tA],["Src Alpha",Hl],["One Minus Src Alpha",Ql],["Dst Alpha",iA],["One Minus Dst Alpha",nA],["Dst Color",sA],["One Minus Dst Color",rA],["Constant Color",Yh],["One Minus Constant Color",$h],["Constant Alpha",jl],["One Minus Constant Alpha",Wl]].map(e=>({label:e[0],value:e[1]}))},{type:"slider",bounds:[0,1],hidden:()=>r.blending!==ir,property:[r,"blendSrcAlpha"]},{type:"slider",bounds:[0,1],hidden:()=>r.blending!==ir,property:[r,"blendDstAlpha"]},{type:"color",hidden:()=>r.blending!==ir||r.blendSrc!==Yh&&r.blendSrc!==$h&&r.blendDst!==Yh&&r.blendDst!==$h,property:[r,"blendColor"]},{type:"slider",hidden:()=>r.blending!==ir||r.blendSrc!==jl&&r.blendSrc!==Wl&&r.blendDst!==jl&&r.blendDst!==Wl,bounds:[0,1],property:[r,"blendAlpha"]},r.alphaMap!==void 0?{type:"image",property:[r,"alphaMap"]}:{},r.alphaMap!==void 0?Ti(r,"alphaMap"):{},{type:"checkbox",label:"Render to Gbuffer",getValue:()=>r.userData.renderToGBuffer===!0,setValue:e=>{!e&&r.userData.renderToGBuffer===!1||(r.userData.renderToGBuffer=e,r.setDirty({change:"userData",key:"renderToGBuffer"}))}},{type:"checkbox",label:"Render to Depth",hidden:()=>r.userData.renderToDepth===void 0,getValue:()=>r.userData.renderToDepth===!0,setValue:e=>{!e&&r.userData.renderToDepth===!1||(r.userData.renderToDepth=e,r.setDirty({change:"userData",key:"renderToDepth"}))}},{type:"input",label:"Forced Linear Depth",getValue:()=>r.userData.forcedLinearDepth??-1,setValue:e=>{e<0&&r.userData.forcedLinearDepth===void 0||(e>=0?r.userData.forcedLinearDepth=e:delete r.userData.forcedLinearDepth,r.setDirty({change:"userData",key:"forcedLinearDepth"}))}},r.isPhysicalMaterial?{type:"checkbox",label:"Inverse AlphaMap",hidden:()=>!r.transparent,getValue:()=>r.userData.inverseAlphaMap===!0,setValue:e=>{r.userData.inverseAlphaMap=e||void 0,r.setDirty({change:"userData",key:"inverseAlphaMap"})}}:{}]}),polygonOffset:r=>({type:"folder",label:"Polygon Offset",children:[{type:"checkbox",label:"Polygon Offset",property:[r,"polygonOffset"]},{type:"slider",label:"Polygon Offset Factor",bounds:[-10,10],property:[r,"polygonOffsetFactor"]},{type:"slider",label:"Polygon Offset Units",bounds:[-10,10],property:[r,"polygonOffsetUnits"]}]}),aoLightMap:r=>({type:"folder",label:"AO/Lightmap",children:[{type:"slider",bounds:[0,2],property:[r,"aoMapIntensity"]},{type:"image",property:[r,"aoMap"]},Ti(r,"aoMap"),{type:"slider",bounds:[0,2],property:[r,"lightMapIntensity"]},{type:"image",property:[r,"lightMap"]},Ti(r,"lightMap")]}),environment:r=>({type:"folder",label:"Environment",children:[{type:"checkbox",label:"Override Environment",getValue:()=>r.userData.separateEnvMapIntensity===!0,setValue:e=>{r.userData.separateEnvMapIntensity=e,e||delete r.userData.separateEnvMapIntensity}},{type:"slider",bounds:[0,20],hidden:()=>!r.userData.separateEnvMapIntensity,label:"Environment Intensity",property:[r,"envMapIntensity"]},{type:"dropdown",hidden:()=>!r.userData.separateEnvMapIntensity&&!r.userData.envMapSlotKey,label:"Environment Map",children:["","environment1","environment2"].map(e=>({label:e||"default",value:e})),getValue:()=>r.userData.envMapSlotKey||"",setValue:e=>{r.userData.envMapSlotKey=e,e||delete r.userData.envMapSlotKey,r.setDirty({change:"userData",key:"envMapSlotKey"})}}]}),misc:r=>[()=>r.materialExtensions?.map(e=>(e.uuid=e.uuid||Ui(),r.__matExtUiConfigs=r.__matExtUiConfigs||{},r.__matExtUiConfigs[e.uuid]||(r.__matExtUiConfigs[e.uuid]=e.getUiConfig?.(r,r.uiConfig?.uiRefresh)),r.__matExtUiConfigs[e.uuid])).filter(e=>e),{type:"dropdown",label:"Side",property:[r,"side"],children:[["Front",fs],["Back",Rn],["Double",Zi]].map(e=>({label:e[0],value:e[1]}))},{type:"input",label:"Mesh count",getValue:()=>r.appliedMeshes.size||0,disabled:!0},{type:"button",label:`Download ${r.constructor.TypeSlug}`,value:()=>{const e=new Blob([JSON.stringify(r.toJSON(),null,2)],{type:"application/json"});ku(e,`material.${r.constructor.TypeSlug}`)}},{type:"button",label:`Select ${r.constructor.TypeSlug}`,value:async()=>Wx(!1,!1,r.constructor.TypeSlug).then(async e=>e?.[0]?.text()).then(e=>{if(!e)return;const t=JSON.parse(e);t.uuid&&delete t.uuid;const i=r.toJSON();return r.fromJSON(t,Fr()),{undo:()=>r.fromJSON(i,Fr()),redo:()=>r.fromJSON(t,Fr())}})}],roughMetal:r=>({type:"folder",label:"Rough/Metal",children:[{type:"slider",bounds:[0,1],property:[r,"roughness"]},{type:"slider",bounds:[0,1],property:[r,"metalness"]},{type:"image",property:[r,"roughnessMap"]},Ti(r,"roughnessMap"),{type:"image",property:[r,"metalnessMap"]},Ti(r,"metalnessMap")]}),bumpNormal:r=>({type:"folder",label:"Bump/Normal",children:[{type:"slider",bounds:[-500,500],stepSize:.001,property:[r,"bumpScale"],hidden:()=>!r.bumpMap},{type:"image",property:[r,"bumpMap"]},Ti(r,"bumpMap"),{type:"image",property:[r,"normalMap"]},{type:"vec2",property:[r,"normalScale"],hidden:()=>!r.normalMap},{type:"dropdown",hidden:()=>!r.normalMap,property:[r,"normalMapType"],children:[["TangentSpace",ks],["ObjectSpace",uw]].map(e=>({label:e[0],value:e[1]}))},Ti(r,"normalMap"),{type:"input",property:[r,"displacementScale"],hidden:()=>!r.displacementMap},{type:"image",property:[r,"displacementMap"]},Ti(r,"displacementMap")]}),emission:r=>({type:"folder",label:"Emission",children:[{type:"color",property:[r,"emissive"]},{type:"slider",bounds:[0,100],property:[r,"emissiveIntensity"]},{type:"image",property:[r,"emissiveMap"]},Ti(r,"emissiveMap")]}),transmission:r=>({type:"folder",label:"Refraction",children:[{type:"slider",bounds:[0,4],property:[r,"ior"]},{type:"slider",bounds:[0,1],property:[r,"transmission"]},{type:"slider",bounds:[0,1],stepSize:.001,property:[r,"thickness"]},{type:"image",property:[r,"transmissionMap"]},Ti(r,"transmissionMap"),{type:"image",property:[r,"thicknessMap"]},Ti(r,"thicknessMap"),{type:"number",property:[r,"attenuationDistance"]},{type:"color",property:[r,"attenuationColor"]}]}),clearcoat:r=>({type:"folder",label:"Clearcoat",children:[{type:"slider",bounds:[0,1],property:[r,"clearcoat"]},{type:"slider",bounds:[0,1],hidden:()=>r.clearcoat<.001,property:[r,"clearcoatRoughness"]},{type:"image",property:[r,"clearcoatMap"]},Ti(r,"clearcoatMap"),{type:"slider",bounds:[0,1],property:[r,"clearcoatRoughness"]},{type:"image",property:[r,"clearcoatRoughnessMap"]},Ti(r,"clearcoatRoughnessMap"),{type:"image",property:[r,"clearcoatNormalMap"]},{type:"vec2",property:[r,"clearcoatNormalScale"],hidden:()=>!r.clearcoatNormalMap},Ti(r,"clearcoatNormalMap")]}),iridescence:r=>({type:"folder",label:"Iridescence",children:[{type:"slider",bounds:[0,3],label:"Intensity",property:[r,"iridescence"]},{type:"slider",bounds:[0,3],label:"IOR",property:[r,"iridescenceIOR"]},{type:"slider",bounds:[0,500],label:"Thickness0",property:[r.iridescenceThicknessRange,"0"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"iridescenceThicknessRange",key:"0"})},{type:"slider",bounds:[0,500],label:"Thickness1",property:[r.iridescenceThicknessRange,"1"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"iridescenceThicknessRange",key:"1"})},{type:"image",property:[r,"iridescenceMap"]},Ti(r,"iridescenceMap"),{type:"image",property:[r,"iridescenceThicknessMap"]},Ti(r,"iridescenceThicknessMap")]}),sheen:r=>({type:"folder",label:"Sheen",children:[{type:"slider",bounds:[0,1],property:[r,"sheen"]},{type:"color",hidden:()=>r.sheen<.001,property:[r,"sheenColor"]},{type:"image",property:[r,"sheenColorMap"]},Ti(r,"sheenColorMap"),{type:"slider",bounds:[0,1],property:[r,"sheenRoughness"]},{type:"image",property:[r,"sheenRoughnessMap"]},Ti(r,"sheenRoughnessMap")]})},Et={name:"",blending:xr,side:fs,vertexColors:!1,opacity:1,transparent:!1,blendSrc:Hl,blendDst:Ql,blendEquation:Sr,blendSrcAlpha:null,blendDstAlpha:null,blendEquationAlpha:null,blendColor:"#000000",blendAlpha:0,depthFunc:ql,depthTest:!0,depthWrite:!0,stencilWriteMask:255,stencilFunc:SA,stencilRef:0,stencilFuncMask:255,stencilFail:ta,stencilZFail:ta,stencilZPass:ta,stencilWrite:!1,clippingPlanes:null,clipIntersection:!1,clipShadows:!1,shadowSide:null,colorWrite:!0,precision:null,polygonOffset:!1,polygonOffsetFactor:0,polygonOffsetUnits:0,dithering:!1,alphaToCoverage:!1,premultipliedAlpha:!1,forceSinglePass:!1,allowOverride:!0,visible:!0,toneMapped:!0,userData:{},alphaTest:0,alphaHash:!1},wa=["opacity","blendColor","blendAlpha","alphaTest"],Ar=class Ar extends ss{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitMaterial=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.onBeforeRender=_e.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=_e.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Unlit Material",uuid:"MBM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...qt.base(this),...vi(this),qt.blending(this),qt.aoLightMap(this),qt.polygonOffset(this),...qt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 outgoingLight = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["ReflectedLight reflectedLight = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=At(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=At(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);_e.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["MeshBasicMaterial","MeshBasicMaterial2",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(_e.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(ke.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};Ar.TypeSlug="bmat",Ar.TYPE="UnlitMaterial",Ar.TypeAlias=["unlit","basic",Ar.TYPE,Ar.TypeSlug,"MeshBasicMaterial","MeshBasicMaterial2"],ke.SerializableMaterials.add(Ar),Ar.MaterialProperties={...Et,color:new se(16777215),map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,specularMap:null,alphaMap:null,envMap:null,combine:Xl,envMapIntensity:1,reflectivity:1,refractionRatio:.98,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",skinning:!1,fog:!0,flatShading:!1},Ar.MapProperties=["map","aoMap","lightMap","specularMap","alphaMap","envMap"],Ar.InterpolateProperties=[...wa,"color","color","specular","emissive","reflectivity","refractionRatio","envMapIntensity","lightMapIntensity","aoMapIntensity","wireframeLinewidth"];let ys=Ar;class HN extends ys{constructor(e){super(e),console.error("MeshBasicMaterial2 is deprecated, use UnlitMaterial instead")}}const _e={threeMaterialPropList:Et,threeMaterialInterpolateProps:wa,setDirty:function(r){r?.needsUpdate!==!1&&(this.needsUpdate=!0),_e.refreshTextureRefs.call(this),this.dispatchEvent({bubbleToObject:!0,bubbleToParent:!0,...r,type:"materialUpdate"}),r?.last!==!1&&r?.refreshUi!==!1&&this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},setValues:r=>function(e,t,i,n){i===void 0&&(i=e.isMaterial),i&&(this.userData={});const s=e?.metadata&&e?.metadata.version<=4.5,a=Xt.enabled;s&&(Xt.enabled=!1);const o=this.constructor.MaterialProperties,l=o?$x(e,{},Array.from(Object.keys(o))):{...e};for(const d of Object.keys(l))l[d]===void 0&&delete l[d];const c=l.userData;delete l.userData;const h=new Set([...this.constructor.InterpolateProperties||ys.InterpolateProperties,...this.constructor.MapProperties||ys.MapProperties]);return n&&rM(l,this,h,n),r.call(this,l),c&&Nv(this.userData,c),this.userData.uuid=this.uuid,(e?.metadata&&e?.metadata.version<=4.6||this.userData.legacyBumpScale)&&this?.bumpScale!==void 0&&this?.bumpMap&&this.defines&&(console.warn("MaterialManager: Old format material loaded, bump map might be incorrect.",e,e.bumpScale),this.defines.BUMP_MAP_SCALE_LEGACY="1",this.userData.legacyBumpScale=!0,this.needsUpdate=!0),s&&(Xt.enabled=a),this.setDirty&&this.setDirty(),this},dispose:r=>function(e=!0){!e&&this.userData.disposeOnIdle===!1||r.call(this)},clone:r=>function(e=!1){e&&(this.userData.cloneId||(this.userData.cloneId="0"),this.userData.cloneCount||(this.userData.cloneCount=0),this.userData.cloneCount+=1);const t=new this.constructor()?.setValues(this,!1)??r.call(this);return e&&(t.userData.cloneId=t.userData.cloneId+"_"+this.userData.cloneCount,t.userData.cloneCount=0,t.name=(t.name||"mat")+"_"+t.userData.cloneId),t},dispatchEvent:r=>function(e){r.call(this,e);const t=e.type;e.bubbleToObject&&(t==="beforeDeserialize"||t==="materialUpdate"||t==="textureUpdate"||t==="select")&&this.appliedMeshes.forEach(i=>i.dispatchEvent({...e,material:this,type:t}))},customProgramCacheKey:function(){return gl.CacheKeyForExtensions(this,this.materialExtensions)+this.userData.inverseAlphaMap},registerMaterialExtensions:function(r){gl.RegisterExtensions(this,r)},unregisterMaterialExtensions:function(r){gl.UnregisterExtensions(this,r)},onBeforeCompile:function(r,e){this.materialExtensions&&gl.ApplyMaterialExtensions(this,r,this.materialExtensions,e),this.dispatchEvent({type:"beforeCompile",shader:r,renderer:e}),r.fragmentShader=r.fragmentShader.replaceAll("#glMarker","// "),r.vertexShader=r.vertexShader.replaceAll("#glMarker","// ")},onBeforeRender:function(r,e,t,i,n){this.defines&&this.envMap!==void 0&&e.fixedEnvMapDirection!==void 0&&(e.fixedEnvMapDirection?this.defines.FIX_ENV_DIRECTION||(this.defines.FIX_ENV_DIRECTION="1",this.needsUpdate=!0):this.defines.FIX_ENV_DIRECTION!==void 0&&(delete this.defines.FIX_ENV_DIRECTION,this.needsUpdate=!0)),this.dispatchEvent({type:"beforeRender",renderer:r,scene:e,camera:t,geometry:i,object:n})},onAfterRender:function(r,e,t,i,n){this.dispatchEvent({type:"afterRender",renderer:r,scene:e,camera:t,geometry:i,object:n})},onBeforeCompileOverride:r=>function(e,t){_e.onBeforeCompile.call(this,e,t),r.call(this,e,t)},onBeforeRenderOverride:r=>function(...e){r.call(this,...e),_e.onBeforeRender.call(this,...e)},onAfterRenderOverride:r=>function(...e){r.call(this,...e),_e.onAfterRender.call(this,...e)},customProgramCacheKeyOverride:r=>function(){return r.call(this)+_e.customProgramCacheKey.call(this)},upgradeMaterial:CM,getMapsForMaterial:function(){const r=new Map;for(const e of this.constructor?.MapProperties||bM)id(e,this,r);if(this.userData)for(const e of wM)id(e,this.userData,r,!0);return r},refreshTextureRefs:function(){this.__textureUpdate||(this.__textureUpdate=QN.bind(this));const r=_e.getMapsForMaterial.call(this),e=new Set([...r.values()]),t=this._mapRefs||new Set;let i=!1;const n=new Set,s=new Set;for(const a of e)!a||!a.isTexture||(a.addEventListener("update",this.__textureUpdate),!t.has(a)&&(i=!0,n.add(a)));for(const a of t)e.has(a)||(a.removeEventListener("update",this.__textureUpdate),i=!0,s.add(a));this._mapRefs=e,i&&this.dispatchEvent({type:"texturesChanged",textures:e,oldTextures:t,addedTextures:n,removedTextures:s,material:this,bubbleToObject:!0,bubbleToParent:!0})}},QN=function(r){!this||this.assetType!=="material"||this.dispatchEvent({texture:r.target,bubbleToParent:!0,bubbleToObject:!0,...r,type:"textureUpdate"})},bM=new Set([]),wM=new Set([]);function CM(){if(!this.isMaterial)return console.error("Material is not a material",this),this;if(this.setDirty||(this.setDirty=_e.setDirty),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.userData.uuid=this.uuid,this.__upgradeSetup||(this.dispatchEvent=_e.dispatchEvent(this.dispatchEvent),this.__upgradeSetup=!0),this.assetType==="material")return this;this.assetType="material",this.setValues=_e.setValues(this.setValues),this.dispose=_e.dispose(this.dispose),this.clone=_e.clone(this.clone),this.extraUniformsToUpload||(this.extraUniformsToUpload={}),this.materialExtensions||(this.materialExtensions=[]),this.registerMaterialExtensions||(this.registerMaterialExtensions=_e.registerMaterialExtensions),this.unregisterMaterialExtensions||(this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions);const r=!this.isDerivedMaterial;return this.onBeforeCompile=r?_e.onBeforeCompileOverride(this.onBeforeCompile):_e.onBeforeCompile,this.onBeforeRender=_e.onBeforeRenderOverride(this.onBeforeRender),this.onAfterRender=_e.onAfterRenderOverride(this.onAfterRender),this.customProgramCacheKey=_e.customProgramCacheKeyOverride(this.customProgramCacheKey),this.setDirty({change:"upgradeMaterial"}),this}const jN=`
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#glMarker importsEnd
#define DEPTH_NORMAL
#define IS_DEPTH_MATERIAL
varying vec3 vViewPosition;
#ifdef USE_ALPHAMAP
#define USE_UV
#endif
void main(){
#include <uv_vertex>
#include <batching_vertex>
#include <beginnormal_vertex>
#include <morphnormal_vertex>
#include <skinbase_vertex>
#include <skinnormal_vertex>
#include <defaultnormal_vertex>
#include <normal_vertex>
#include <begin_vertex>
#include <morphtarget_vertex>
#include <skinning_vertex>
#include <displacementmap_vertex>
#include <project_vertex>
#include <logdepthbuf_vertex>
#include <clipping_planes_vertex>
#glMarker beforeOutput
vViewPosition=-mvPosition.xyz;}`,WN=`
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
#glMarker importsEnd
#define DEPTH_NORMAL
#define IS_DEPTH_MATERIAL
varying vec3 vViewPosition;
#ifdef USE_ALPHAMAP
#define USE_UV
#include <packing>
#endif
#if IS_GLSL3 > 0
#ifndef gl_FragColor
layout(location=0)out vec4 gDepthNormal;layout(location=1)out vec4 gFlags;
#endif
#endif
uniform vec2 cameraNearFar;uniform vec4 flags;vec2 pack16(float value){float f=clamp(value,0.0,1.0)*255.0;float digitLow=fract(f);float digitHigh=floor(f)/255.0;return vec2(digitHigh,digitLow);}vec2 packNormal(vec3 n){float p=sqrt(n.z*8.0+8.0);return vec2(n.xy/p+0.5);}float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}void main(){
#glMarker mainStart
#include <clipping_planes_fragment>
vec4 diffuseColor=vec4(1.0);
#include <map_fragment>
#ifdef USE_ALPHAMAP
float alphaMapValue=
#ifdef ALPHA_I_RGBA_PACKING
1.-unpackRGBAToDepth(texture2D(alphaMap,vAlphaMapUv));
#else
texture2D(alphaMap,vAlphaMapUv).g;
#endif
#if defined(INVERSE_ALPHAMAP) && INVERSE_ALPHAMAP >= 1
diffuseColor.a*=1.0-alphaMapValue;
#else
diffuseColor.a*=alphaMapValue;
#endif
#endif
#include <alphatest_fragment>
#include <logdepthbuf_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#glMarker beforeOutput
#ifdef FORCED_LINEAR_DEPTH
float linearZ=float(FORCED_LINEAR_DEPTH);
#else
float linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);
#endif
vec2 packedZ=pack16(pow(max(0.,linearZ),0.5));vec2 packedNormal=packNormal(normal);
#if IS_GLSL3 > 0
#ifndef gl_FragColor
gDepthNormal=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);gFlags=flags;
#else
gl_FragColor=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);
#endif
#else
gl_FragColor=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);
#endif
}`,Fh=class Fh extends nn{constructor({customMaterialExtensions:e,...t}={},i=!1){super(),this.assetType="material",this.isAShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.type="ShaderMaterial",this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.isRawShaderMaterial=i,i&&(this.type="RawShaderMaterial"),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){_e.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a),_e.onBeforeRender.call(this,e,t,i,n,s,a)}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),_e.onAfterRender.call(this,e,t,i,n,s,a)}setValues(e){return _e.setValues(super.setValues).call(this,e)}toJSON(e){throw new Error("Method not supported for this material.")}fromJSON(e,t){throw new Error("Method not supported for this material.")}get materialObject(){return this}};Fh.TypeSlug="shaderMat",Fh.TYPE="ShaderMaterial2",Fh.MaterialProperties={...Et,fragmentShader:"",vertexShader:"",uniforms:{},defines:{},extensions:{},isRawShaderMaterial:!1,uniformsGroups:{},wireframe:!1,wireframeLinewidth:1,clipping:!1,lights:!1,fog:!1,glslVersion:null,defaultAttributeValues:{}},Fh.InterpolateProperties=[...wa,"wireframeLinewidth"];let gd=Fh;class km extends gd{constructor(e=!0,t){super({vertexShader:jN,fragmentShader:WN,uniforms:ko.merge([Re.common,Re.bumpmap,Re.normalmap,Re.displacementmap,{cameraNearFar:{value:new $(.1,1e3)},flags:{value:new rt(255,255,255,255)}}]),defines:{IS_GLSL3:e?"1":"0"},glslVersion:e?EA:GP,...t}),this.flagUpdaters=new Map,this.normalMapType=ks,this.flatShading=!1,this.reset()}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a);let o=!1,l=s.material;if(Array.isArray(l)&&(l=l[0]),l===this&&(l=s.currentMaterial,o=!0),Array.isArray(l)&&(l=l[0]),!l)return;if(o)ba({FORCED_LINEAR_DEPTH:l.userData.forcedLinearDepth??void 0},this);else{const h=u=>{const d=l[u];d&&(this.uniforms[u].value=d,this.uniforms[u+"Transform"]?d.isTexture&&e.materials.refreshTransformUniform(d,this.uniforms[u+"Transform"]):console.error("GBufferMaterial: "+u+"Transform is not defined in uniform"))};h("map"),l.side!==void 0&&(this.side=l.side??Zi),h("alphaMap"),l.alphaTest!==void 0&&(this.alphaTest=l.alphaTest<1e-4?1e-4:l.alphaTest),l.alphaHash!==void 0&&(this.alphaHash=l.alphaHash),h("bumpMap"),l.bumpScale!==void 0&&(this.uniforms.bumpScale.value=l.bumpScale),h("normalMap"),l.normalScale!==void 0&&this.uniforms.normalScale.value.copy(l.normalScale),l.normalMapType!==void 0&&(this.normalMapType=l.normalMapType),l.flatShading!==void 0&&(this.flatShading=l.flatShading),h("displacementMap"),l.displacementScale!==void 0&&(this.uniforms.displacementScale.value=l.displacementScale),l.displacementBias!==void 0&&(this.uniforms.displacementBias.value=l.displacementBias),l.wireframe!==void 0&&(this.wireframe=l.wireframe),l.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=l.wireframeLinewidth),ba({ALPHAMAP_UV:this.uniforms.alphaMap.value?"uv":void 0,USE_DISPLACEMENTMAP:this.uniforms.displacementMap.value?1:void 0,DISPLACEMENTMAP_UV:this.uniforms.displacementMap.value?"uv":void 0,ALPHA_I_RGBA_PACKING:l.userData.ALPHA_I_RGBA_PACKING?1:void 0,FORCED_LINEAR_DEPTH:l.userData.forcedLinearDepth??void 0},this)}const c=this.uniforms.flags.value;this._updateFlagsUniform(c,l,e,t,i,n,s),i.updateShaderProperties(this),this.uniformsNeedUpdate=!0,l.materialExtensions?.length&&this.registerMaterialExtensions(l.materialExtensions),this.needsUpdate=!0,e.resetCurrentMaterial&&e.resetCurrentMaterial()}_updateFlagsUniform(e,t,i,n,s,a,o){e.set(255,255,255,255);const l=t.userData.gBufferData?.materialId??t.userData.matId;e.z=l||0,this.flagUpdaters.forEach(c=>c(e,{material:t,renderer:i,scene:n,camera:s,geometry:a,object:o})),e.x/=255,e.y/=255,e.z/=255,e.w/=255}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a);let o=s.material;Array.isArray(o)&&(o=o[0]),!(!o||o===this)&&(o.materialExtensions?.length&&this.unregisterMaterialExtensions(o.materialExtensions),this.reset())}reset(){this.uniforms.map.value=null,this.side=Zi,this.uniforms.alphaMap.value=null,this.alphaTest=.001,this.alphaHash=!1,this.uniforms.bumpMap.value=null,this.uniforms.bumpScale.value=1,this.uniforms.normalMap.value=null,this.uniforms.normalScale.value.set(1,1),this.normalMapType=ks,this.flatShading=!1,this.uniforms.displacementMap.value=null,this.uniforms.displacementScale.value=1,this.uniforms.displacementBias.value=0,this.uniforms.flags.value.set(255,255,255,255),this.wireframe=!1,this.wireframeLinewidth=1}}class qN extends km{constructor(e,t){super(e,t),console.warn("DepthNormalMaterial is deprecated, use GBufferMaterial instead")}}function XN(r,e=new km(!0,{blending:gn,transparent:!1})){return e.onBeforeCompile=t=>{if(t.__modified)return;t.__modified=!0;let i=r.material;if(i===e&&(i=r.currentMaterial),!i.isLineMaterial)return;t.uniforms={...i.uniforms,...t.uniforms};const n=t.fragmentShader.split("void main()")[0].split("#glMarker importsEnd")[1]||"",s=`
vec3 normal = vec3(0.,0.,1.);
`+t.fragmentShader.split("#glMarker beforeOutput")[1];t.fragmentShader=At(i.fragmentShader,"void main()",n+`
`,{prepend:!0}),t.fragmentShader=At(t.fragmentShader,"#include <logdepthbuf_fragment>",s+`
//end-frag-patch
`,{append:!0}),t.fragmentShader=t.fragmentShader.split("//end-frag-patch")[0];const a=t.vertexShader.split("void main()")[0].split("#glMarker importsEnd")[1]||"",o=t.vertexShader.split("#glMarker beforeOutput")[1].replace(/}\s*$/,"")+`
`;t.vertexShader=At(i.vertexShader,"void main()",a,{prepend:!0}),t.vertexShader=At(t.vertexShader,"#include <clipping_planes_vertex>",o,{append:!0})},e}function YN(r,e=new xc({depthPacking:tc,blending:gn,transparent:!1})){return e.onBeforeCompile=t=>{if(t.__modified)return;t.__modified=!0;let i=r.material;if(i===e&&(i=r.currentMaterial),!i.isLineMaterial)return;t.uniforms={...i.uniforms,...t.uniforms},t.defines={...i.defines,...t.defines};const n=`
varying vec2 vHighPrecisionZW;
#include <packing>
`,s=t.fragmentShader.split("#include <logdepthbuf_fragment>")[1];t.fragmentShader=At(i.fragmentShader,"void main()",n,{prepend:!0}),t.fragmentShader=At(t.fragmentShader,"#include <logdepthbuf_fragment>",s+`
//end-frag-patch
`,{append:!0}),t.fragmentShader=t.fragmentShader.split("//end-frag-patch")[0];const a=`
varying vec2 vHighPrecisionZW;
`,o=`
vHighPrecisionZW = gl_Position.zw;
`;t.vertexShader=At(i.vertexShader,"void main()",a,{prepend:!0}),t.vertexShader=At(t.vertexShader,"#include <clipping_planes_vertex>",o,{append:!0})},e}const Ge={setDirty:function(r,...e){typeof r=="string"&&(r={change:r}),this.dispatchEvent({bubbleToParent:this.userData?.autoUpdateParent??!0,object:this,...r,type:"objectUpdate",args:e}),r?.refreshUi!==!1&&r?.last!==!1&&this.refreshUi&&this.refreshUi()},upgradeObject3D:TM,makeUiConfig:pM,autoCenter:function(r=!0,e=!1){if(e){if(!this.userData.autoCentered||!this.userData._lastCenter)return this;if(!isFinite(this.userData._lastCenter.lengthSq()))return this;this.position.add(this.userData._lastCenter),delete this.userData.autoCentered,delete this.userData.isCentered,delete this.userData._lastCenter}else{const i=new In().expandByObject(this,!0,!0).getCenter(new x);if(!isFinite(i.lengthSq()))return this;this.userData._lastCenter=i,this.position.sub(i),this.userData.autoCentered=!0,this.userData.isCentered=!0}return this.updateMatrix(),r&&this.setDirty&&this.setDirty({change:"autoCenter",undo:e}),this},autoScale:function(r,e,t=!0,i=!1){let n=1;if(i){if(!this.userData.autoScaled||!this.userData._lastScaleRadius)return this;const s=this.userData.autoScaleRadius||r||1;if(n=this.userData._lastScaleRadius/s,!isFinite(n))return this;this.userData.autoScaled=!0,this.userData.autoScaleRadius=r,delete this.userData._lastScaleRadius}else{const a=new In().expandByObject(this,!0,!0).getSize(new x).length()*.5;if(r===void 0&&(r=this.userData.autoScaleRadius||1),n=r/a,!isFinite(n))return this;this.userData.autoScaled=!0,this.userData.autoScaleRadius=r,this.userData._lastScaleRadius=a}return this.userData.pseudoCentered?this.children.forEach(s=>{s.scale.multiplyScalar(n)}):this.scale.multiplyScalar(n),(e||this.userData.isCentered)&&this.position.multiplyScalar(n),this.traverse(s=>{const a=s;a.isLight&&a.shadow?.camera?.right&&(a.shadow.camera.right*=n,a.shadow.camera.left*=n,a.shadow.camera.top*=n,a.shadow.camera.bottom*=n,s.setDirty&&s.setDirty()),a.isCamera&&a.right&&(a.right*=n,a.left*=n,a.top*=n,a.bottom*=n,s.setDirty&&s.setDirty())}),t&&this.setDirty&&this.setDirty({change:"autoScale",undo:i}),this},pivotToBoundsCenter:function(r=!0){const t=new In().expandByObject(this,!0,!0).getCenter(new x);return Ge.pivotToPoint.call(this,t,r)},pivotToPoint:function(r,e=!0,t=!0){const i=new x().copy(r),n=new x().copy(i),s=new pe().copy(this.matrixWorld).invert(),a=this.parent?.matrixWorld,o=new pe;a!==void 0&&o.copy(a).invert(),i.applyMatrix4(o);const l=this.position.clone();this.position.copy(i),n.applyMatrix4(s).negate();const c=new Map;if(this.geometry){const h=t?this.geometry.appliedMeshes:void 0;if(h)for(const u of h){if(u===this)continue;c.set(u,u.position.clone()),u.updateMatrix();const d=new x(-n.x,-n.y,-n.z).applyMatrix4(u.matrix);u.position.copy(d),e&&u.setDirty&&u.setDirty({change:"pivotToPoint"})}this.geometry.translate(n.x,n.y,n.z)}return this.children.forEach(h=>{h.position.add(n)}),e&&this.setDirty&&this.setDirty({change:"pivotToPoint",undo:!1}),()=>{if(this.position.copy(l),this.geometry){this.geometry.translate(-n.x,-n.y,-n.z);for(const[h,u]of c)h.position.copy(u),e&&h.setDirty&&h.setDirty({change:"pivotToPoint"})}this.children.forEach(h=>{h.position.sub(n)}),e&&this.setDirty&&this.setDirty({change:"pivotToPoint",undo:!0})}},traverseModels:function(r,{visible:e=!1,widgets:t=!1,...i}){if(!this.assetType||!t&&this.assetType==="widget"||e&&!this.visible||r(this)===!1)return;const s=this.children;for(let a=0,o=s.length;a<o;a++){const l=s[a];!l.assetType||!l.traverseModels||l.traverseModels(r,{visible:e,widgets:t,...i})}},eventCallbacks:{onAddedToParent:function(r){const e=this.parent?.parentRoot??this.parent;e!==this.parentRoot&&this.traverse(t=>{const i=t.parentRoot;i!==e&&(t.parentRoot=e,t.dispatchEvent({...r,type:"parentRootChanged",object:t,oldParentRoot:i||void 0,bubbleToParent:!1}))}),!this.objectProcessor&&e?.objectProcessor&&this.traverse(t=>{t.objectProcessor=e.objectProcessor,t.objectProcessor?.processObject(t)}),this.setDirty?.({...r,change:"addedToParent"})},onRemovedFromParent:function(r){this.setDirty?.({...r,change:"removedFromParent"}),this.parentRoot&&this.traverse(e=>{const t=e.parentRoot;t&&(e.parentRoot=void 0,e.dispatchEvent({...r,type:"parentRootChanged",object:e,oldParentRoot:t||void 0,bubbleToParent:!1}))})},onGeometryUpdate:function(r){r.bubbleToObject&&this.dispatchEvent({bubbleToParent:!0,...r,object:this,geometry:r.geometry})}},initMaterial:function(){if(qn(this,"_currentMaterial"))return;this._currentMaterial=null;const{protoDesc:r}=nv(this,"material"),e=this.material;delete this.material,Object.defineProperty(this,"currentMaterial",{configurable:!0,enumerable:!0,get(){return r?.get?r.get.call(this):Ge.getMaterial.call(this)},set(t){Ge.setMaterial.call(this,t),r?.set?.call(this,t)}}),Object.defineProperty(this,"material",{configurable:!0,enumerable:!0,get(){return this.forcedOverrideMaterial??this.currentMaterial},set(t){this.forcedOverrideMaterial&&console.warn("IObject3D: Material is being set on an object with forcedOverrideMaterial set"),this.currentMaterial=t}}),Object.defineProperty(this,"materials",{configurable:!0,enumerable:!0,get:Ge.getMaterials,set:Ge.setMaterials}),this.material=e,(this.isLineSegments2||this.isLine2||this.isWireframe)&&(Object.defineProperty(this,"customDepthMaterial",{configurable:!0,enumerable:!0,get:()=>this._customDepthMaterial?this._customDepthMaterial:(this._customDepthMaterial=YN(this),this._customDepthMaterial),set:t=>{this._customDepthMaterial=t,t&&(t.needsUpdate=!0),this.setDirty&&this.setDirty({change:"customDepthMaterial"})}}),Object.defineProperty(this,"customGBufferMaterial",{configurable:!0,enumerable:!0,get:()=>this._customGBufferMaterial?this._customGBufferMaterial:(this._customGBufferMaterial=XN(this),this._customGBufferMaterial),set:t=>{this._customGBufferMaterial=t,t&&(t.needsUpdate=!0),this.setDirty&&this.setDirty({change:"customDepthMaterial"})}})),this.setMaterial||(this.setMaterial=t=>{const i=this.material;return console.error("IObject3D: setMaterial is deprecated, use material property directly"),this.material=t,i})},getMaterial:function(){return this._currentMaterial||void 0},getMaterials:function(){const r=this.currentMaterial;return r?Array.isArray(r)?[...r]:[r]:[]},setMaterial:function(r){const e=(Array.isArray(r)?r:[r]).filter(o=>o);if(this.material==e||e.length===1&&this.material===e[0])return[];const t=this.material,i=Array.isArray(t)?[...t]:[t];let n=[];const s=[];for(const o of i)o&&n.push(o);const a=[];for(const o of e)o&&(o.assetType||_e.upgradeMaterial.call(o),n.includes(o)?n=n.filter(l=>l!==o):s.push(o),a.push(o));for(const o of n)o.dispatchEvent({type:"removeFromMesh",object:this});for(const o of s)o.dispatchEvent({type:"addToMesh",object:this});this._currentMaterial=a.length?a.length!==1?a:a[0]||null:null,this.dispatchEvent({type:"materialChanged",material:this._currentMaterial??null,oldMaterial:t??null,object:this,bubbleToParent:!0}),this.refreshUi&&this.refreshUi()},setMaterials:function(r){this.currentMaterial=r||void 0},initGeometry:function(){this._currentGeometry=null;const{protoDesc:r}=nv(this,"geometry"),e=this.geometry;delete this.geometry,Object.defineProperty(this,"geometry",{configurable:!0,enumerable:!0,get(){return this.forcedOverrideGeometry??(r?.get?r.get.call(this):Ge.getGeometry.call(this))},set(t){this.forcedOverrideGeometry&&console.warn("IObject3D: Geometry is being set on an object with forcedOverrideGeometry set"),Ge.setGeometry.call(this,t),r?.set?.call(this,t)}}),this.geometry=e,this.setGeometry||(this.setGeometry=t=>{const i=this.geometry;return console.error("IObject3D: setGeometry is deprecated, use geometry property directly"),this.geometry=t,i})},getGeometry:function(){return this._currentGeometry||void 0},setGeometry:function(r){const e=this.geometry||void 0;e!==r&&(e&&this._onGeometryUpdate&&e.removeEventListener("geometryUpdate",this._onGeometryUpdate),r&&(r.assetType||ri.upgradeGeometry.call(r)),this._currentGeometry=r||null,r&&this._onGeometryUpdate&&r.addEventListener("geometryUpdate",this._onGeometryUpdate),this.dispatchEvent({type:"geometryChanged",geometry:r??null,oldGeometry:e,bubbleToParent:!0,object:this}),this.refreshUi&&this.refreshUi())},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},dispatchEvent:r=>function(e){if(!(e.target&&e.target!==this&&this.acceptChildEvents===!1)){if(e.bubbleToParent||this.userData?.__autoBubbleToParentEvents?.includes(e.type)){const t=this.parentRoot||this.parent;this.parentRoot!==this&&t?.dispatchEvent(e)}r.call(this,e)}},clone:r=>function(e,...t){const i=this.userData;this.userData={};const n=r.call(this,e,...t);if(this.userData=i,Sm(n.userData,i),Ge.upgradeObject3D.call(n),n.userData.cloneParent=this.uuid,this._sChildren)if(e){n._sChildren=[];for(const s of this._sChildren){if(!s)continue;let a;if(this.children.includes(s)){const o=this.children.indexOf(s);a=n.children[o]}else a=s.clone(!0);n._sChildren.push(a)}}else n._sChildren=[...this._sChildren];return n},copy:r=>function(e,...t){const i=this.isLight?this.target:null,n=e.userData;e.userData={};const s=this.userData;return r.call(this,e,...t),this.userData=s,e.userData=n,Sm(this.userData,e.userData),i&&this.target&&(i.position.copy(this.target.position),i.updateMatrixWorld(),this.target=i),this},add:r=>function(...e){if(this.autoUpgradeChildren!==!1)for(const t of e)Ge.upgradeObject3D.call(t);return r.call(this,...e)},dispose:r=>function(e=!0){e&&this.parent&&(this.removeFromParent(),delete this.parentRoot),this.dispatchEvent({type:"dispose",bubbleToParent:!1});for(const t of[...this.children])t?.dispose&&t.dispose(!1);return r&&r.call(this),this},getMapsForObject3D:function(){const r=new Map;for(const e of this.constructor?.MapProperties||MM)id(e,this,r);if(this.isScene)for(const e of EM)id(e,this,r);return r},deleteObject:async(r,e)=>{if(!(e?.shiftKey?!0:await f.ThreeViewer.Dialog.confirm("Delete Object: Are you sure you want to delete this object?")))return;const i=r.parent;return r.dispose&&r.dispose(!0),()=>{i&&i.add(r)}},duplicateObject:async(r,e)=>{const t=r.parent,i=r.clone(!0);Nm(r,i);const n=e?!e.shiftKey:!1;return{action:()=>{t&&!i.parent&&t.add(i),n&&i.dispatchEvent({type:"select",value:i,object:i,ui:!!e,bubbleToParent:!0,trackUndo:!1})},undo:()=>{i.parent===t&&i.removeFromParent()}}}};function Ad(r){const e=new Set(r);return r.filter(t=>{let i=t.parent;for(;i;){if(e.has(i))return!1;i=i.parent}return!0})}async function xM(r){const e=Ad(r);if(!e.length)return;const t=e.map(s=>s.name||s.uuid.slice(0,8)).join(", ");if(!await f.ThreeViewer.Dialog.confirm(`Delete ${e.length} object${e.length>1?"s":""}: ${t}?`))return;const n=new Map;for(const s of e)n.set(s,s.parent);for(const s of e)s.dispose&&s.dispose(!0);return{undo:()=>{for(const s of e){const a=n.get(s);a&&a.add(s)}},redo:()=>{for(const s of e)s.dispose&&s.dispose(!0)}}}function SM(r){const e=Ad(r),t=[],i=new Map;for(const n of e){const s=n.clone(!0);Nm(n,s),i.set(s,n.parent),t.push(s)}for(const n of t){const s=i.get(n);s&&!n.parent&&s.add(n)}return{clones:t,undo:()=>{for(const n of t)n.removeFromParent()},redo:()=>{for(const n of t){const s=i.get(n);s&&!n.parent&&s.add(n)}}}}const EM=new Set(["environmentMap","background"]),MM=new Set([]);function TM(r){if(!this)return this;if(this.userData||(this.userData={}),this.__objectSetup)return this;if(this.__objectSetup=!0,this.objectExtensions||(this.objectExtensions=[]),this.userData.__autoBubbleToParentEvents||(this.userData.__autoBubbleToParentEvents=["select"]),this.isLight?this.assetType="light":this.isCamera?this.assetType="camera":this.isWidget?this.assetType="widget":this.assetType="model",r&&(this.parentRoot=r.parentRoot||r),this.dispatchEvent=Ge.dispatchEvent(this.dispatchEvent),this.dispose=Ge.dispose(this.dispose),this.clone=Ge.clone(this.clone),this.copy=Ge.copy(this.copy),this.add=Ge.add(this.add),this.setDirty||(this.setDirty=Ge.setDirty),this.refreshUi||(this.refreshUi=Ge.refreshUi),this.autoScale||(this.autoScale=Ge.autoScale.bind(this)),this.autoCenter||(this.autoCenter=Ge.autoCenter.bind(this)),this.pivotToBoundsCenter||(this.pivotToBoundsCenter=Ge.pivotToBoundsCenter.bind(this)),this.pivotToPoint||(this.pivotToPoint=Ge.pivotToPoint.bind(this)),this.traverseModels||(this.traverseModels=Ge.traverseModels.bind(this)),this.addEventListener("added",Ge.eventCallbacks.onAddedToParent),this.addEventListener("removed",Ge.eventCallbacks.onRemovedFromParent),(this.isLineSegments2||this.isLine2)&&(this.isMesh=!0),(this.isMesh||this.isLine)&&!this.__meshSetup){if(this.__meshSetup=!0,this._onGeometryUpdate=e=>Ge.eventCallbacks.onGeometryUpdate.call(this,e),Ge.initMaterial.call(this),Ge.initGeometry.call(this),!this.userData.__keepShadowDef){const e=Array.isArray(this.material)?this.material[0]:this.material;this.castShadow=!e||!e.transparent&&!e.transmission,this.receiveShadow=!0,this.userData.__keepShadowDef=!0}this.addEventListener("dispose",()=>{(this.materials||[this.material]).forEach(e=>e?.dispose(!1)),this.geometry?.dispose(!1)})}if(!this.uiConfig&&(this.assetType==="model"||this.assetType==="camera")&&Ge.makeUiConfig.call(this),this.autoUpgradeChildren!==!1){const e=[...this.children];for(const t of e)TM.call(t,this)}return!this.modelObject&&Object.defineProperty(this,"modelObject",{get:()=>(console.error("IObject3D: modelObject is deprecated, use object directly"),this)}),this}var $N=Object.defineProperty,KN=Object.getOwnPropertyDescriptor,Qs=(r,e,t,i)=>{for(var n=i>1?void 0:i?KN(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&$N(e,t,n),n};f.CameraView=class extends wi{constructor(e,t,i,n,s,a=1,o){super(),this.uuid=Ui(),this.name="Camera View",this.position=new x,this.target=new x,this.quaternion=new Qe,this.zoom=1,this.duration=1,this.isWorldSpace=!0,this.set=l=>this.dispatchEvent({type:"setView",camera:l,view:this}),this.update=l=>this.dispatchEvent({type:"updateView",camera:l,view:this}),this.delete=l=>this.dispatchEvent({type:"deleteView",camera:l,view:this}),this.animate=(l,c)=>this.dispatchEvent({type:"animateView",camera:l,duration:c,view:this}),this.setDirty=l=>{this.dispatchEvent({...l,type:"update"}),this.uiConfig&&(l?.key==="name"?(this.uiConfig.label=this.name,this.uiConfig.uiRefresh?.()):this.uiConfig.uiRefresh?.(!0,"postFrame"))},e!==void 0&&(this.name=e),t&&this.position.copy(t),i&&this.target.copy(i),n&&this.quaternion.copy(n),s!==void 0&&(this.zoom=s),a!==void 0&&a!==0&&(this.duration=a),o!==void 0&&(this.isWorldSpace=o)}clone(){return new f.CameraView(this.name,this.position,this.target,this.quaternion,this.zoom,this.duration,this.isWorldSpace)}},Qs([tt("setDirty"),z(),Fe()],f.CameraView.prototype,"name",2),Qs([tt("setDirty"),z(),gi()],f.CameraView.prototype,"position",2),Qs([tt("setDirty"),z(),gi()],f.CameraView.prototype,"target",2),Qs([tt("setDirty"),z(),gi()],f.CameraView.prototype,"quaternion",2),Qs([tt("setDirty"),z(),Lt()],f.CameraView.prototype,"zoom",2),Qs([tt("setDirty"),z(),Lt()],f.CameraView.prototype,"duration",2),Qs([tt("setDirty"),z()],f.CameraView.prototype,"isWorldSpace",2),Qs([lt()],f.CameraView.prototype,"set",2),Qs([lt()],f.CameraView.prototype,"update",2),Qs([lt()],f.CameraView.prototype,"delete",2),Qs([lt()],f.CameraView.prototype,"animate",2),f.CameraView=Qs([Vc("CameraView"),Aa("Camera View")],f.CameraView);function IM(r){const e="chordal",t=r.map(l=>l.position.clone()),i=new Oc(t,!0,e,.75),n=(l,c,h)=>{h=h||new x;const u=1/t.length,p=((c===0?t.length:c)-1)*u;return i.getPointAt(p+l*u,h),h},s=r.map(l=>l.target.clone()),a=new Oc(s,!0,e,.75);return{getPosition:n,getTarget:(l,c,h)=>{h=h||new x;const u=1/s.length,p=((c===0?s.length:c)-1)*u;return a.getPointAt(p+l*u,h),h}}}const ct={setDirty:function(r){if(!this._positionWorld)return;const e=typeof r=="string",t=e?r:r?.change??r?.key;let i=!1;r?.projectionUpdated!==!1&&(!t||["zoom","fov","left","right","top","bottom","aspect","frustumSize","view","coordinateSystem","projection","activateMain","deactivateMain","near","far","nearFar","deserialize"].includes(t))&&(this.updateProjectionMatrix(),i=!0),i=i||r?.projectionUpdated||!1,e&&(r=void 0),this.getWorldPosition(this._positionWorld),this.controls&&this.controls.target&&this.controls.enabled!==!1&&this.target!==this.controls.target?this.controls.target.copy(this.target):this.userData.autoLookAtTarget&&this.lookAt(this.target),this.dispatchEvent({...r,type:"update",bubbleToParent:!1,camera:this}),this.dispatchEvent({...r,type:"cameraUpdate",projectionUpdated:i,bubbleToParent:!0,camera:this}),Ge.setDirty.call(this,{refreshScene:!1,...r,projectionUpdated:i})},activateMain:function(r={},e=!1,t=!0,i){if(!e)return r.camera===null?this.deactivateMain(r,e,t):this.dispatchEvent({type:"activateMain",...r,camera:this,bubbleToParent:!0});this.userData.__isMainCamera||(this.userData.__isMainCamera=!0,this.userData.__lastScale=this.scale.clone(),this.scale.divide(this.getWorldScale(new x)),i&&this.setCanvas?this.setCanvas(i,t):t&&(this.refreshCameraControls(!1),this.refreshAspect(!1)),this.setDirty({change:"activateMain",...r}))},deactivateMain:function(r={},e=!1,t=!0,i=!1){if(!e)return this.dispatchEvent({type:"activateMain",...r,camera:void 0,bubbleToParent:!0});this.userData.__isMainCamera&&(this.userData.__isMainCamera=!1,this.userData.__lastScale&&(this.scale.copy(this.userData.__lastScale),delete this.userData.__lastScale),i?this.setCanvas(void 0,t):t&&this.refreshCameraControls(!1),t&&this.refreshCameraControls(!1),this.setDirty({change:"deactivateMain",...r}))},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},refreshTarget:function(r=4,e=!0){this.controls?.enabled&&this.controls.target?this.controls.target!==this.target&&this.target.copy(this.controls.target):this.getWorldDirection(this.target).multiplyScalar(r).add(this.getWorldPosition(new x)),e&&this.setDirty({change:"target"})},refreshAspect:function(r=!0){if(this.autoAspect)if(!this._canvas)console.warn("ICamera: cannot calculate aspect ratio without canvas/container");else{let e=this._canvas.clientWidth/this._canvas.clientHeight;isFinite(e)||(e=1),this.aspect=e,this.refreshFrustum&&this.refreshFrustum(!1)}r&&this.setDirty({change:"aspect"})},updateShaderProperties:function(r){return r.uniforms.cameraPositionWorld?.value?.copy(this._positionWorld),r.uniforms.cameraNearFar?.value?.set(this.near,this.far),r.uniforms.projection&&(r.uniforms.projection.value=this.projectionMatrix),r.defines.PERSPECTIVE_CAMERA=this.type==="PerspectiveCamera"?"1":"0",r.defines.ORTHOGRAPHIC_CAMERA=this.type==="OrthographicCamera"?"1":"0",this},upgradeCamera:JN,copy:r=>function(e,t,i,n,...s){if(!e.isCamera)return console.error("ICamera.copy: camera is not a Camera",e),this;if(r.call(this,e,t,...s),e.target?.isVector3)this.target.copy(e.target);else{const a=this.controls?.minDistance??i??4;e.getWorldDirection(this.target).multiplyScalar(a).add(this.getWorldPosition(new x))}if(n){const a=e.getWorldPosition(this.position);this.parent&&this.position.copy(this.parent.worldToLocal(a))}return this.updateMatrixWorld(!0),this.updateProjectionMatrix(),this.refreshAspect(!1),this.setDirty(),this},getView:function(r=!0,e){const t=new x;this.updateWorldMatrix(!0,!1);const i=this.matrixWorld;t.x=i.elements[4],t.y=i.elements[5],t.z=i.elements[6],t.normalize();const n=e||new f.CameraView;n.name=this.name,n.position.copy(this.position),n.target.copy(this.target),n.quaternion.copy(this.quaternion),n.zoom=this.zoom;const s=this.parent;return s&&(r?(n.position.applyMatrix4(s.matrixWorld),this.getWorldQuaternion(n.quaternion)):t.transformDirection(s.matrixWorld.clone().invert())),n.isWorldSpace=r,n},setView:function(r){this.position.copy(r.position),this.target.copy(r.target),this.quaternion.copy(r.quaternion),this.zoom=r.zoom,this.setDirty()},fitObject:function(r,e=1.5,t){const i=Array.isArray(r)?r:[r];if(!i.length)return;const n=new In().expandByObject(i[0],!1,!0);for(let p=1;p<i.length;p++)n.expandByObject(i[p],!1,!0);const s=xm(this,n),a=n.getCenter(new x);n.getSize(new x).lengthSq()<=0&&i[0].getWorldPosition(a);const l=t?.min??.5,c=t?.max??50,h=Math.min(c,Math.max(l,s*e)),u=this.getView(!0);u.target.copy(a);const d=new x().subVectors(u.target,u.position).normalize();u.position.copy(d.multiplyScalar(-h).add(u.target)),this.setView(u)},setViewFromCamera:function(r,e,t=!0){this.copy(r,void 0,e,t)},setViewToMain:function(r){this.dispatchEvent({type:"setView",...r,camera:this,bubbleToParent:!0})},setNearFar(r,e,t,i,n){const s=Math.abs(r.near-e)+Math.abs(r.far-t)>.001;return r.near=e,r.far=t,i&&s&&r.setDirty?(r.setDirty({change:"nearFar",source:n}),!0):(r.updateProjectionMatrix(),!1)},defaultMinNear:.1,defaultMaxFar:1e3};function JN(){if(!this.isCamera){console.error("Object is not a camera",this);return}this.userData.__cameraSetup||(this.userData.__cameraSetup=!0,Ge.upgradeObject3D.call(this),this.copy=ct.copy(this.copy),this.target||(this.target=new x),this._positionWorld||(this._positionWorld=new x),this.refreshTarget||(this.refreshTarget=ct.refreshTarget),this.refreshAspect||(this.refreshAspect=ct.refreshAspect),this.updateShaderProperties||(this.updateShaderProperties=ct.updateShaderProperties),this.activateMain||(this.activateMain=ct.activateMain),this.deactivateMain||(this.deactivateMain=ct.deactivateMain),this.refreshUi||(this.refreshUi=ct.refreshUi),this.setDirty||(this.setDirty=ct.setDirty),this.getView||(this.getView=ct.getView),this.setView||(this.setView=ct.setView),this.fitObject||(this.fitObject=ct.fitObject),this.setViewFromCamera||(this.setViewFromCamera=ct.setViewFromCamera),this.setViewToMain||(this.setViewToMain=ct.setViewToMain),this.setCanvas||(this.setCanvas=()=>eh("setCanvas")),this.setControlsCtor||(this.setControlsCtor=()=>eh("setControlsCtor")),this.removeControlsCtor||(this.removeControlsCtor=()=>eh("removeControlsCtor")),this.refreshCameraControls||(this.refreshCameraControls=()=>eh("refreshCameraControls")),this.setInteractions||(this.setInteractions=()=>eh("setInteractions")),this.dispose||(this.dispose=()=>eh("dispose")),this.assetType="camera")}function eh(r){console.warn(`ICamera.${r} is not supported on this object. Please use objects of PerspectiveCamera2 or OrthographicCamera2 classes.`)}var ZN=Object.defineProperty,vn=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&ZN(e,t,n),n};const Ii=class extends Vi{constructor(e,t,i,n,s){super(n,s),this.assetType="camera",this._currentControlsMode="",this.userData={},this.target=new x(0,0,0),this.near=.1,this.far=2e3,this.autoLookAtTarget=!1,this.autoNearFar=!0,this.minNearPlane=void 0,this.maxFarPlane=void 0,this.dollyFov=!1,this._interactionsDisabledBy=new Set,this.refreshAspect=ct.refreshAspect,this.refreshUi=ct.refreshUi,this.refreshTarget=ct.refreshTarget,this.activateMain=ct.activateMain,this.deactivateMain=ct.deactivateMain,this.updateShaderProperties=ct.updateShaderProperties,this.controlsCtors=new Map([["orbit",(a,o)=>{const l=o?o.ownerDocument?o:o.documentElement:document.body,c=new f.OrbitControls3(a,l);return l.tabIndex===-1&&(l.tabIndex=1e3,l.style.outline="none"),c.listenToKeyEvents(l),c.screenSpacePanning=!0,c}]]),this._controlsChanged=()=>{this._controls&&this._controls.target&&this.refreshTarget(void 0,!1),this.setDirty({change:"controls"})},this.getView=ct.getView,this.setView=ct.setView,this.fitObject=ct.fitObject,this.setViewFromCamera=ct.setViewFromCamera,this.setViewToMain=ct.setViewToMain,this._positionWorld=new x,this._camUi=[...vi(this)||[],{type:"input",label:"Dolly FoV",property:[this,"dollyFov"]},...Um.call(this),Fm.call(this)],this.uiConfig={type:"folder",label:()=>this.name||"Camera",children:[...this._camUi,()=>this._controls?.zoomIn?{type:"button",label:"Zoom in",value:()=>this._controls?.zoomIn(1)}:{},()=>this._controls?.zoomOut?{type:"button",label:"Zoom out",value:()=>this._controls?.zoomOut(1)}:{},()=>this._controls?.uiConfig]},this._canvas=t,this.autoAspect=i??!!t,ct.upgradeCamera.call(this),this.controlsMode=e||"",this.refreshTarget(void 0,!1),this.setDirty()}get controls(){return this._controls}get isMainCamera(){return this.userData&&this.userData.__isMainCamera||!1}get interactionsEnabled(){return this._interactionsDisabledBy.size===0}setInteractions(e,t,i=!0){const n=this._interactionsDisabledBy.size;e?this._interactionsDisabledBy.delete(t):this._interactionsDisabledBy.add(t),n!==this._interactionsDisabledBy.size&&this.refreshCameraControls(i)}get canUserInteract(){return this._interactionsDisabledBy.size===0&&this.isMainCamera&&this.controlsMode!==""}setDirty(e){ct.setDirty.call(this,e),e?.last!==!1&&this._camUi?.forEach(t=>t?.uiRefresh?.(!1,"postFrame",1))}setControlsCtor(e,t,i=!1){if(!i&&this.controlsCtors.has(e)){console.error("PerspectiveCamera2: "+e+" already exists.");return}this.controlsCtors.set(e,t)}removeControlsCtor(e){this.controlsCtors.delete(e)}_initCameraControls(){const e=this.controlsMode;this._controls=this.controlsCtors.get(e)?.(this,this._canvas)??void 0,!this._controls&&e!==""&&console.error("ICamera - Unable to create controls with mode "+e+". Are you missing a plugin?"),this._controls?.addEventListener&&this._controls.addEventListener("change",this._controlsChanged),this._currentControlsMode=this._controls?e:""}_disposeCameraControls(){this._controls&&(this._controls.target===this.target&&(this._controls.target=new x),this._controls.removeEventListener&&this._controls.removeEventListener("change",this._controlsChanged),this._controls.dispose&&this._controls.dispose()),this._currentControlsMode="",this._controls=void 0}refreshCameraControls(e=!0){if(this.controlsCtors){if(this._controls?(this._currentControlsMode!==this.controlsMode||this!==this._controls.object||this._controls.domElement&&this._canvas!==this._controls.domElement)&&(this._disposeCameraControls(),this._initCameraControls()):this._initCameraControls(),this._controls){const t=this.canUserInteract;this._controls.enabled=t,t&&this.up.copy(ft.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t){if((e.camOptions||e.aspect==="auto")&&(e={...e}),e.camOptions){const i=e.camOptions;i.fov&&(e.fov=i.fov),i.focus&&(e.focus=i.focus),i.zoom&&(e.zoom=i.zoom),i.aspect&&(e.aspect=i.aspect),i.controlsMode&&(e.controlsMode=i.controlsMode),delete e.camOptions}return e.aspect==="auto"&&(e.aspect=this.aspect,this.autoAspect=!0),ke.Deserialize(e,this,t,!0),this.refreshAspect(!1),this.setDirty({change:"deserialize"}),this}dispose(){this._disposeCameraControls()}setCanvas(e,t=!0){this._canvas=e,t&&(this.refreshCameraControls(),this.refreshAspect(!1))}get isActiveCamera(){return this.isMainCamera}getControls(){return this._controls}get cameraObject(){return this}get modelObject(){return this}targetUpdated(e=!0){e&&this.setDirty()}};vn([Fe("Name")],Ii.prototype,"name"),vn([z("camControls")],Ii.prototype,"_controls"),vn([Oi("Controls Mode",void 0,r=>({children:["none",...r.controlsCtors.keys()].map(e=>({label:e,value:e==="none"?"":e}))})),z(),ei(Ii.prototype.refreshCameraControls)],Ii.prototype,"controlsMode"),vn([z()],Ii.prototype,"userData"),vn([tt(Ii.prototype.setDirty),Oe("Field Of View",[1,180],.001),z()],Ii.prototype,"fov"),vn([tt(Ii.prototype.setDirty),z()],Ii.prototype,"focus"),vn([tt(Ii.prototype.setDirty),Lt("FoV Zoom"),z()],Ii.prototype,"zoom"),vn([gi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"position"})})),z()],Ii.prototype,"position"),vn([gi("Up",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"up"})})),z()],Ii.prototype,"up"),vn([gi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"rotation"}),disabled:()=>r.autoLookAtTarget}))],Ii.prototype,"rotation"),vn([gi("Target",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"target"}),disabled:()=>!r.autoLookAtTarget})),z()],Ii.prototype,"target"),vn([z(),ei("refreshAspect"),ae("Auto Aspect")],Ii.prototype,"autoAspect"),vn([z(),ei("refreshAspect"),Lt("Aspect Ratio",r=>({hidden:()=>r.autoAspect}))],Ii.prototype,"aspect"),vn([Vt({obj:"userData",onChange:"setDirty"})],Ii.prototype,"autoLookAtTarget"),vn([Vt({obj:"userData",onChange:"setDirty"})],Ii.prototype,"autoNearFar"),vn([Vt({obj:"userData",onChange:"setDirty"})],Ii.prototype,"minNearPlane"),vn([Vt({obj:"userData",onChange:"setDirty"})],Ii.prototype,"maxFarPlane"),vn([Vt({obj:"userData"})],Ii.prototype,"dollyFov"),vn([de((r,e)=>{e||console.warn("Setting camera invisible is not supported",r,e)})],Ii.prototype,"visible");let th=Ii;class PM extends th{constructor(e,t,i,n){super(void 0,void 0,void 0,e,t||1),this.dollyFov=!1,(i||n)&&(this.autoNearFar=!1,i&&(this.near=i,this.minNearPlane=i),n&&(this.far=n,this.maxFarPlane=n))}}var ek=Object.defineProperty,tk=Object.getOwnPropertyDescriptor,on=(r,e,t,i)=>{for(var n=i>1?void 0:i?tk(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&ek(e,t,n),n};const fi=class extends Mr{constructor(e,t,i,n,s,a,o,l,c,h,u){super(s,a,o,l,c,h),this.assetType="camera",this._currentControlsMode="",this.userData={},this._frustumSize=void 0,this.target=new x(0,0,0),this.near=.1,this.far=2e3,this.autoLookAtTarget=!1,this.autoNearFar=!0,this.minNearPlane=void 0,this.maxFarPlane=void 0,this._interactionsDisabledBy=new Set,this.refreshAspect=ct.refreshAspect,this.refreshUi=ct.refreshUi,this.refreshTarget=ct.refreshTarget,this.activateMain=ct.activateMain,this.deactivateMain=ct.deactivateMain,this.updateShaderProperties=ct.updateShaderProperties,this.controlsCtors=new Map([["orbit",(d,p)=>{const m=p?p.ownerDocument?p:p.documentElement:document.body,A=new f.OrbitControls3(d,m);return m.tabIndex===-1&&(m.tabIndex=1e3,m.style.outline="none"),A.listenToKeyEvents(m),A.screenSpacePanning=!0,A}]]),this._controlsChanged=()=>{this._controls&&this._controls.target&&this.refreshTarget(void 0,!1),this.setDirty({change:"controls"})},this.getView=ct.getView,this.setView=ct.setView,this.fitObject=ct.fitObject,this.setViewFromCamera=ct.setViewFromCamera,this.setViewToMain=ct.setViewToMain,this._positionWorld=new x,this._camUi=[...vi(this)||[],...Um.call(this),Fm.call(this)],this.uiConfig={type:"folder",label:()=>this.name||"Camera",children:[...this._camUi,()=>this._controls?.uiConfig]},this._canvas=t,this.aspect=u||1,this._frustumSize=n??4,this.autoAspect=i??!!t,ct.upgradeCamera.call(this),this.controlsMode=e||"",this.refreshTarget(void 0,!1),this.refreshFrustum(!1),this.setDirty()}get controls(){return this._controls}get isMainCamera(){return this.userData&&this.userData.__isMainCamera||!1}get frustumSize(){return this._frustumSize??0}set frustumSize(e){this._frustumSize=e<=0?void 0:e,this.refreshFrustum(!1),this.setDirty()}get interactionsEnabled(){return this._interactionsDisabledBy.size===0}setInteractions(e,t){const i=this._interactionsDisabledBy.size;e?this._interactionsDisabledBy.delete(t):this._interactionsDisabledBy.add(t),i!==this._interactionsDisabledBy.size&&this.refreshCameraControls(!0)}get canUserInteract(){return this._interactionsDisabledBy.size===0&&this.isMainCamera&&this.controlsMode!==""}setDirty(e){ct.setDirty.call(this,e),e?.last!==!1&&this._camUi?.forEach(t=>t?.uiRefresh?.(!1,"postFrame",1))}refreshFrustum(e=!0){this._frustumSize!==void 0&&(this.top=this._frustumSize/2,this.bottom=-this.top,this.left=this.bottom*this.aspect,this.right=this.top*this.aspect,e&&this.setDirty())}setControlsCtor(e,t,i=!1){if(!i&&this.controlsCtors.has(e)){console.error("OrthographicCamera2: "+e+" already exists.");return}this.controlsCtors.set(e,t)}removeControlsCtor(e){this.controlsCtors.delete(e)}_initCameraControls(){const e=this.controlsMode;this._controls=this.controlsCtors.get(e)?.(this,this._canvas)??void 0,!this._controls&&e!==""&&console.error("ICamera - Unable to create controls with mode "+e+". Are you missing a plugin?"),this._controls?.addEventListener&&this._controls.addEventListener("change",this._controlsChanged),this._currentControlsMode=this._controls?e:""}_disposeCameraControls(){this._controls&&(this._controls.target===this.target&&(this._controls.target=new x),this._controls.removeEventListener&&this._controls.removeEventListener("change",this._controlsChanged),this._controls.dispose&&this._controls.dispose()),this._currentControlsMode="",this._controls=void 0}refreshCameraControls(e=!0){if(this.controlsCtors){if(this._controls?(this._currentControlsMode!==this.controlsMode||this!==this._controls.object||this._controls.domElement&&this._canvas!==this._controls.domElement)&&(this._disposeCameraControls(),this._initCameraControls()):this._initCameraControls(),this._controls){const t=this.canUserInteract;this._controls.enabled=t,t&&this.up.copy(ft.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t){return ke.Deserialize(e,this,t,!0),this.setDirty({change:"deserialize"}),this}dispose(){this._disposeCameraControls()}setCanvas(e,t=!0){this._canvas=e,t&&(this.refreshCameraControls(),this.refreshAspect(!1))}get isActiveCamera(){return this.isMainCamera}getControls(){return this._controls}get cameraObject(){return this}get modelObject(){return this}targetUpdated(e=!0){e&&this.setDirty()}};on([Fe("Name")],fi.prototype,"name",2),on([z("camControls")],fi.prototype,"_controls",2),on([Oi("Controls Mode",void 0,r=>({children:["none",...r.controlsCtors.keys()].map(e=>({label:e,value:e==="none"?"":e}))})),z(),ei(fi.prototype.refreshCameraControls)],fi.prototype,"controlsMode",2),on([z()],fi.prototype,"userData",2),on([tt(fi.prototype.setDirty),Lt("Zoom"),z()],fi.prototype,"zoom",2),on([tt(fi.prototype.setDirty),Lt("Left",r=>({hidden:()=>r._frustumSize!==void 0})),z()],fi.prototype,"left",2),on([tt(fi.prototype.setDirty),Lt("Right",r=>({hidden:()=>r._frustumSize!==void 0})),z()],fi.prototype,"right",2),on([tt(fi.prototype.setDirty),Lt("Top",r=>({hidden:()=>r._frustumSize!==void 0})),z()],fi.prototype,"top",2),on([tt(fi.prototype.setDirty),Lt("Bottom",r=>({hidden:()=>r._frustumSize!==void 0})),z()],fi.prototype,"bottom",2),on([Fe("Frustum Size")],fi.prototype,"frustumSize",1),on([gi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"position"})})),z()],fi.prototype,"position",2),on([gi("Up",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"up"})})),z()],fi.prototype,"up",2),on([gi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"rotation"}),disabled:()=>r.autoLookAtTarget}))],fi.prototype,"rotation",2),on([gi("Target",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"target"}),disabled:()=>!r.autoLookAtTarget})),z()],fi.prototype,"target",2),on([z(),ei("refreshAspect"),ae("Auto Aspect")],fi.prototype,"autoAspect",2),on([z(),ei("refreshAspect"),Lt("Aspect Ratio",r=>({hidden:()=>r.autoAspect}))],fi.prototype,"aspect",2),on([Vt({obj:"userData",onChange:"setDirty"})],fi.prototype,"autoLookAtTarget",2),on([Vt({obj:"userData",onChange:"setDirty"})],fi.prototype,"autoNearFar",2),on([Vt({obj:"userData",onChange:"setDirty"})],fi.prototype,"minNearPlane",2),on([Vt({obj:"userData",onChange:"setDirty"})],fi.prototype,"maxFarPlane",2),on([de((r,e)=>{e||console.warn("Setting camera invisible is not supported",r,e)})],fi.prototype,"visible",2);let yd=fi;class DM extends yd{constructor(e,t,i,n,s,a){super(void 0,void 0,void 0,void 0,e,t,i,n,s,a,1),(s!==void 0||a)&&(this.autoNearFar=!1,s&&(this.near=s,this.minNearPlane=s),a&&(this.far=a,this.maxFarPlane=a))}}class RM extends gd{constructor(e,t,i=!1){super(e,i),this.textures=[],this.setTextureIds(t)}setTextureIds(e){this.textures.map(t=>t.id).join(";")!==e.join(";")&&(this.textures=e.map(t=>({id:t,colorSpace:Dt})),this.setDirty())}_setUniformTexSize(e,t){if(!t||!e)return;const i=t?.width??512,n=t?.height??512,s=e.value;s.isVector2||console.warn("uniform is not a Vector2"),s&&Math.abs(s.x-i)+Math.abs(s.y-n)>.1&&(s.x=i,s.y=n,this.uniformsNeedUpdate=!0)}onBeforeRender(e,t,i,n,s,a){this.uniforms.screenSize&&this._setUniformTexSize(this.uniforms.screenSize,e.getRenderTarget()??e.getSize(new $));for(const o of this.textures){const l=o.id,c=this.uniforms[l]?.value;c&&(this._setUniformTexSize(this.uniforms[l+"Size"],c.image),c.colorSpace!==o.colorSpace&&(o.colorSpace=c.colorSpace,this.needsUpdate=!0))}super.onBeforeRender(e,t,i,n,s,a)}onBeforeCompile(e,t){const i=`
`+this.textures.map(n=>`uniform sampler2D ${n.id}; 
`+bv(n.id??"input",n.colorSpace)).join(`
`);e.fragmentShader.includes("#include <encodings_pars_fragment>")?e.fragmentShader=At(e.fragmentShader,"#include <encodings_pars_fragment>",i,{append:!0}):e.fragmentShader.includes("precision highp float;")?e.fragmentShader=At(e.fragmentShader,"precision highp float;",i,{append:!0}):e.fragmentShader=i+e.fragmentShader,super.onBeforeCompile(e,t)}customProgramCacheKey(){return super.customProgramCacheKey()+this.textures.map(e=>e.id+e.colorSpace).join(";")}}const yr=class yr extends Nc{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isPhysicalMaterial=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.map=null,this.alphaMap=null,this.roughnessMap=null,this.metalnessMap=null,this.normalMap=null,this.bumpMap=null,this.displacementMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.onAfterRender=_e.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Physical Material",uuid:"MPM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...qt.base(this),...vi(this),qt.blending(this),qt.roughMetal(this),qt.bumpNormal(this),qt.emission(this),qt.transmission(this),qt.environment(this),qt.aoLightMap(this),qt.clearcoat(this),qt.iridescence(this),qt.sheen(this),qt.polygonOffset(this),...qt.misc(this)]},this.fog=!1,this.attenuationDistance=0,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 totalDiffuse = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["#include <lights_physical_fragment>","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=At(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=At(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);e.fragmentShader=At(e.fragmentShader,"#include <opaque_fragment>",`gl_FragColor = clamp(gl_FragColor, 0.0, 1000.0);
`,{append:!0}),_e.onBeforeCompile.call(this,e,t),e.defines&&(e.defines.INVERSE_ALPHAMAP=this.userData.inverseAlphaMap?1:0),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a),_e.onBeforeRender.call(this,e,t,i,n,s,a);const o=this.userData.inverseAlphaMap?1:0;o!==this.defines.INVERSE_ALPHAMAP&&(this.defines.INVERSE_ALPHAMAP=o,this.needsUpdate=!0)}setValues(e,t=!0,i=void 0,n){if(e){if(e.type&&!t&&!["MeshPhysicalMaterial","MeshStandardMaterial","MeshStandardMaterial2",this.constructor.TYPE,this.type].includes(e.type)){console.error("Material type is not supported:",e.type);return}typeof e.normalScale=="number"&&(e.normalScale=[e.normalScale,e.normalScale]),e.ior!==void 0&&(this.ior=e.ior),_e.setValues(super.setValues).call(this,e,t,i,n),isFinite(this.attenuationDistance)||(this.attenuationDistance=0),this.userData.uuid=this.uuid}}copy(e){return this.setValues(e,!1),this}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(ke.Deserialize(e,this,t,!0),this.setValues(e),this):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};yr.TypeSlug="pmat",yr.TYPE="PhysicalMaterial",yr.TypeAlias=["physical","standard",yr.TYPE,yr.TypeSlug,"MeshStandardMaterial","MeshStandardMaterial2","MeshPhysicalMaterial"],ke.SerializableMaterials.add(yr),yr.MaterialProperties={...Et,color:new se(16777215),roughness:1,metalness:0,map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,emissive:"#000000",emissiveIntensity:1,emissiveMap:null,bumpMap:null,bumpScale:1,normalMap:null,normalMapType:ks,normalScale:new $(1,1),displacementMap:null,displacementScale:1,displacementBias:0,roughnessMap:null,metalnessMap:null,alphaMap:null,envMap:null,envMapRotation:new Tt,envMapIntensity:1,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",flatShading:!1,fog:!0,clearcoat:0,clearcoatMap:null,clearcoatRoughness:0,clearcoatRoughnessMap:null,clearcoatNormalScale:new $(1,1),clearcoatNormalMap:null,dispersion:0,reflectivity:.5,iridescence:0,iridescenceMap:null,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],iridescenceThicknessMap:null,sheen:0,sheenColor:new se(0),sheenColorMap:null,sheenRoughness:1,sheenRoughnessMap:null,transmission:0,transmissionMap:null,thickness:0,thicknessMap:null,attenuationDistance:1/0,attenuationColor:new se(1,1,1),specularIntensity:1,specularIntensityMap:null,specularColor:new se(1,1,1),specularColorMap:null,anisotropy:0,anisotropyRotation:0,anisotropyMap:null},yr.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap","envMap","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","specularIntensityMap","specularColorMap","anisotropyMap"],yr.InterpolateProperties=[...wa,"color","emissive","roughness","metalness","lightMapIntensity","aoMapIntensity","emissiveIntensity","bumpScale","normalScale","displacementScale","displacementBias","envMapIntensity","wireframeLinewidth","reflectivity","clearcoat","clearcoatRoughness","clearcoatNormalScale","iridescence","iridescenceIOR","iridescenceThicknessRange","sheen","sheenColor","sheenRoughness","transmission","thickness","attenuationDistance","attenuationColor","specularIntensity","specularColor","anisotropy","anisotropyRotation"];let ai=yr;class ik extends ai{constructor(e){super(e),console.error("MeshStandardMaterial2 is deprecated, use UnlitMaterial instead")}}const Qr=class Qr extends nn{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isObjectShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.onBeforeRender=_e.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=_e.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Shader Material",uuid:"OSM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...vi(this),...qt.base(this),qt.blending(this),qt.polygonOffset(this),...qt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){_e.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["ShaderMaterial","ShaderMaterial2","ExtendedShaderMaterial",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(_e.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(ke.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};Qr.TypeSlug="shmat",Qr.TYPE="ObjectShaderMaterial",Qr.TypeAlias=["shader",Qr.TYPE,Qr.TypeSlug,"ShaderMaterial"],ke.SerializableMaterials.add(Qr),Qr.MaterialProperties={...Et,defines:{},uniforms:{},uniformsGroups:[],vertexShader:"",fragmentShader:"",linewidth:1,wireframe:!1,wireframeLinewidth:1,fog:!1,lights:!1,clipping:!1,forceSinglePass:!0,extensions:{derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},defaultAttributeValues:{color:[1,1,1],uv:[0,0],uv1:[0,0]},index0AttributeName:void 0,uniformsNeedUpdate:!1,glslVersion:null,flatShading:!1},Qr.InterpolateProperties=[...wa,"linewidth","wireframeLinewidth"];let h0=Qr;const vr=class vr extends Ei{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitLineMaterial=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.onBeforeRender=_e.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=_e.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Unlit Line Material",uuid:"MBLM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[{type:"input",property:[this,"name"]},{type:"checkbox",property:[this,"vertexColors"]},{type:"color",property:[this,"color"]},Ti(this,"map"),{type:"number",property:[this,"linewidth"]},{type:"dropdown",property:[this,"linecap"],children:["butt","round","square"].map(i=>({label:i}))},{type:"dropdown",property:[this,"linejoin"],children:["bevel","round","miter"].map(i=>({label:i}))},qt.blending(this),qt.polygonOffset(this),...qt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 outgoingLight = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["ReflectedLight reflectedLight = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=At(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=At(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);_e.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["LineBasicMaterial","LineBasicMaterial2",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(_e.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(ke.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};vr.TypeSlug="blmat",vr.TYPE="UnlitLineMaterial",vr.TypeAlias=["unlitline","basicline",vr.TYPE,vr.TypeSlug,"LineBasicMaterial"],ke.SerializableMaterials.add(vr),vr.MaterialProperties={...Et,color:new se(16777215),map:null,linewidth:1,linecap:"round",linejoin:"round",fog:!0},vr.MapProperties=["map"],vr.InterpolateProperties=[...wa,"color","linewidth"];let $n=vr;class nk extends $n{constructor(e){super(e),console.error("LineBasicMaterial2 is deprecated, use UnlitLineMaterial instead")}}var sk=Object.defineProperty,hr=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&sk(e,t,n),n};const js=(Fs=class extends $c{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLineMaterial2=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.autoUpdateResolution=!0,this.uiConfig={type:"folder",label:"Line Material",uuid:"MPM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...vi(this)||[],qt.blending(this),qt.polygonOffset(this),...qt.misc(this)]},this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec4 diffuseColor = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#ifdef USE_COLOR","mainStart"]];for(const s of n)e.vertexShader=At(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=At(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);_e.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,s,a){this.autoUpdateResolution&&e.getSize(this.resolution),super.onBeforeRender(e,t,i,n,s,a),_e.onBeforeRender.call(this,e,t,i,n,s,a)}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),_e.onAfterRender.call(this,e,t,i,n,s,a)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["LineMaterial",this.constructor.TYPE,this.type].includes(e.type)&&!e.isLineMaterial&&!e.isLineMaterial2?(console.error("Material type is not supported:",e.type),this):(_e.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(ke.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}},Fs.TypeSlug="lmat",Fs.TYPE="LineMaterial2",Fs.TypeAlias=["line",Fs.TYPE,Fs.TypeSlug,"LineMaterial"],ke.SerializableMaterials.add(Fs),Fs.MaterialProperties={...Et,color:new se(16777215),dashed:!1,dashScale:1,dashSize:1,dashOffset:0,gapSize:1,linewidth:1,resolution:new $(1,1),alphaToCoverage:!1,worldUnits:!1,uniforms:{},defines:{},extensions:{},clipping:!1,fog:!0,fragmentShader:"",vertexShader:""},Fs.InterpolateProperties=[...wa,"color","dashScale","dashSize","dashOffset","gapSize","linewidth","resolution"],Fs);hr([Fe()],js.prototype,"name"),hr([Tn()],js.prototype,"color"),hr([ae()],js.prototype,"dashed"),hr([Lt()],js.prototype,"dashScale"),hr([Lt()],js.prototype,"dashSize"),hr([Lt()],js.prototype,"dashOffset"),hr([Lt()],js.prototype,"gapSize"),hr([Lt()],js.prototype,"linewidth"),hr([gi()],js.prototype,"resolution"),hr([ae()],js.prototype,"alphaToCoverage"),hr([ae()],js.prototype,"worldUnits");let ji=js;class rk extends ji{}const _r=class _r extends Ko{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLegacyPhongMaterial=!0,this.appliedMeshes=new Set,this.setDirty=_e.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=_e.registerMaterialExtensions,this.unregisterMaterialExtensions=_e.unregisterMaterialExtensions,this.onBeforeRender=_e.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=_e.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Phong Material",uuid:"MBM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...qt.base(this),qt.blending(this),qt.polygonOffset(this),qt.aoLightMap(this),{type:"folder",label:"Specular",children:[{type:"color",property:[this,"specular"]},{type:"image",property:[this,"specularMap"]},Ti(this,"specularMap"),{type:"slider",label:"Shininess",property:[this,"shininess"],bounds:[0,100],stepSize:.1},{type:"slider",label:"Reflectivity",property:[this,"reflectivity"],bounds:[0,1],stepSize:.01},{type:"slider",label:"Refraction Ratio",property:[this,"refractionRatio"],bounds:[0,3],stepSize:.01}]},qt.bumpNormal(this),qt.emission(this),{type:"folder",label:"Env Map",children:[{type:"image",property:[this,"envMap"]},Ti(this,"envMap"),{type:"slider",label:"Env Map Intensity",property:[this,"envMapIntensity"],bounds:[0,5],stepSize:.01}]},...qt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),_e.upgradeMaterial.call(this),this.setValues(t)}dispose(){return _e.dispose(super.dispose).call(this)}clone(e=!1){return _e.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+_e.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 outgoingLight = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["ReflectedLight reflectedLight = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=At(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=At(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);_e.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["MeshPhongMaterial","MeshPhongMaterial2",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(_e.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...ke.Serialize(this,e,!0)}:ke.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(ke.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};_r.TypeSlug="phongmat",_r.TYPE="LegacyPhongMaterial",_r.TypeAlias=["phong",_r.TYPE,_r.TypeSlug,"MeshPhongMaterial"],ke.SerializableMaterials.add(_r),_r.MaterialProperties={...Et,color:new se(16777215),specular:new se(1118481),shininess:30,map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,emissive:new se(0),emissiveIntensity:1,emissiveMap:null,bumpMap:null,bumpScale:1,normalMap:null,normalMapType:"TangentSpaceNormalMap",normalScale:new $(1,1),displacementMap:null,displacementScale:1,displacementBias:0,specularMap:null,alphaMap:null,envMap:null,combine:Xl,envMapIntensity:1,reflectivity:1,refractionRatio:.98,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",skinning:!1,fog:!0,flatShading:!1},_r.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","specularMap","alphaMap","envMap"],_r.InterpolateProperties=[...wa,"color","specular","emissive","shininess","lightMapIntensity","aoMapIntensity","emissiveIntensity","bumpScale","normalScale","displacementScale","displacementBias","envMapIntensity","reflectivity","refractionRatio","wireframeLinewidth"];let Gm=_r;class BM extends ft{constructor(){super(),this.assetType="model",this.setDirty=Ge.setDirty,this.refreshUi=Ge.refreshUi,Ge.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class Al extends Ri{constructor(){super(),this.assetType="model",this.setDirty=Ge.setDirty,this.refreshUi=Ge.refreshUi,Ge.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class zm extends ye{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=Ge.setDirty,this.refreshUi=Ge.refreshUi,Ge.upgradeObject3D.call(this)}get modelObject(){return this}}class ak extends Bc{constructor(e,t,i=1){super(e,t,i),this.assetType="model",this.setDirty=Ge.setDirty,this.refreshUi=Ge.refreshUi,Ge.upgradeObject3D.call(this)}get modelObject(){return this}}class vd extends Hs{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,i=new Float32Array(2*t);for(let n=0;n<t;n+=3)i[2*n]=e[n],i[2*n+1]=e[n+1],i[2*n+2]=e[n+2],i[2*n+3]=e[n+3],i[2*n+4]=e[n+4],i[2*n+5]=e[n+5];return super.setPositions(i),this}setColors(e){const t=e.length-3,i=new Float32Array(2*t);for(let n=0;n<t;n+=3)i[2*n]=e[n],i[2*n+1]=e[n+1],i[2*n+2]=e[n+2],i[2*n+3]=e[n+3],i[2*n+4]=e[n+4],i[2*n+5]=e[n+5];return super.setColors(i),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class Vm extends _a{constructor(e=new vd,t=new $c({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}class u0 extends Vm{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=Ge.setDirty,this.refreshUi=Ge.refreshUi,this.isMeshLine=!0,Ge.upgradeObject3D.call(this)}get modelObject(){return this}}class LM extends _a{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=Ge.setDirty,this.refreshUi=Ge.refreshUi,this.isMeshLineSegments=!0,Ge.upgradeObject3D.call(this)}get modelObject(){return this}}class _d extends $e{constructor(){super(),this.center2=ri.center2,this.setDirty=ri.setDirty,this.refreshUi=ri.refreshUi,this.appliedMeshes=new Set,ri.upgradeGeometry.call(this)}}class d0 extends vd{constructor(){super(),this.center2=ri.center2,this.setDirty=ri.setDirty,this.refreshUi=ri.refreshUi,this.appliedMeshes=new Set,ri.upgradeGeometry.call(this)}getPositions(){return OM(this.attributes.instanceStart)}getColors(){return OM(this.attributes.instanceColorStart)}}function OM(r){const e=r?.data.array;if(!e)return null;const t=e.length/2+3,i=new Float32Array(t);i[0]=e[0],i[1]=e[1],i[2]=e[2];for(let n=3;n<t;n+=3){const s=2*n-3;i[n]=e[s],i[n+1]=e[s+1],i[n+2]=e[s+2]}return i}class UM extends Hs{constructor(){super(),this.center2=ri.center2,this.setDirty=ri.setDirty,this.refreshUi=ri.refreshUi,this.appliedMeshes=new Set,ri.upgradeGeometry.call(this)}getPositions(){return this.attributes.instanceStart?.data.array||null}getColors(){return this.attributes.instanceColorStart?.data.array||null}}class f0 extends Hs{constructor(e){super(),this.isWireframeGeometry2=!0,this.type="WireframeGeometry2",this.fromWireframeGeometry(new Ip(e))}}class ok extends f0{constructor(e){super(e),this.center2=ri.center2,this.setDirty=ri.setDirty,this.refreshUi=ri.refreshUi,this.appliedMeshes=new Set,ri.upgradeGeometry.call(this)}}class FM extends $e{constructor(e,t,i=32,n=64,s=!1,a=new $(1,1),o="shape"){super(),this.type="TubeShapeGeometry",this.parameters={path:t,shape:e,shapeSegments:i,tubularSegments:n,closed:s,primary:o,shapeScale:a.clone()};const l=t.computeFrenetFrames(n,s);this.frames=l;const c=new x,h=new x,u=new x,d=new $;let p=new x;const m=[],A=[],g=[],y=e.getSpacedPoints(i);for(const S of y)S.multiply(a);v(),this.setIndex(g),this.setAttribute("position",new Me(m,3)),this.setAttribute("uv",new Me(A,2)),this.computeVertexNormals();const _=this.attributes.normal;M();function v(){for(let S=0;S<n;S++)b(S);b(s===!1?n:0),E(),T()}function b(S){p=t.getPointAt(S/n,p);const w=l.normals[S],C=l.binormals[S];for(let D=0;D<=i;D++){const O=y[D%i];h.set(0,0,0).addScaledVector(w,O.x).addScaledVector(C,O.y),c.copy(p).add(h),m.push(c.x,c.y,c.z)}}function T(){const S=o==="shape",w=S?i:n,C=S?n:i;for(let D=1;D<=w;D++)for(let O=1;O<=C;O++){const[F,G]=S?[O,D]:[D,O],j=(i+1)*(F-1)+(G-1),W=(i+1)*F+(G-1),K=(i+1)*F+G,q=(i+1)*(F-1)+G;g.push(j,W,q),g.push(W,K,q)}}function E(){for(let S=0;S<=n;S++)for(let w=0;w<=i;w++)d.x=S/n,d.y=w/i,A.push(d.x,d.y)}function M(){for(let w=1;w<i;w++){const C=w+n*(i+1);h.fromBufferAttribute(_,w),u.fromBufferAttribute(_,C),h.add(u).normalize(),_.setXYZ(w,h.x,h.y,h.z),_.setXYZ(C,h.x,h.y,h.z)}for(let w=1;w<n;w++){const C=w*(i+1),D=C+i;h.fromBufferAttribute(_,C),u.fromBufferAttribute(_,D),h.add(u).normalize(),_.setXYZ(C,h.x,h.y,h.z),_.setXYZ(D,h.x,h.y,h.z)}h.fromBufferAttribute(_,0),u.fromBufferAttribute(_,i),h.add(u);const S=n*(i+1);u.fromBufferAttribute(_,S),h.add(u),u.fromBufferAttribute(_,S+i),h.add(u),h.normalize(),_.setXYZ(0,h.x,h.y,h.z),_.setXYZ(i,h.x,h.y,h.z),_.setXYZ(S,h.x,h.y,h.z),_.setXYZ(S+i,h.x,h.y,h.z),_.needsUpdate=!0}}createSplits(e){this.clearGroups();const t=this.parameters.primary==="shape"?this.parameters.shapeSegments:this.parameters.tubularSegments,i=this.index.count,n=[...e,1].sort((o,l)=>o-l);let s=0,a=0;for(const o of n){const l=Math.round(t*o)*i/t;this.addGroup(s,l-s,a++),s=l}return this.groups.length}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e.shape=this.parameters.shape.toJSON(),e}}const J_=class J_ extends qo{constructor(e,t,i,n,s,a,o,l){super(e,t,i,n,s,a,o,l),this.type="EllipseCurve3D"}getPoint(e,t){return super.getPoint(e,t||new x)}};Bt.SerializableClasses.set("EllipseCurve3D",J_);let yl=J_;const pn={setDirty:function(r,...e){typeof r=="string"&&(r={change:r}),Ge.setDirty.call(this,r,...e)},upgradeLight:lk,refreshUi:Ge.refreshUi};function lk(r){this&&Ge.upgradeObject3D.call(this,r)}var ck=Object.defineProperty,Hm=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&ck(e,t,n),n};class vl extends Rp{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Ambient Light",children:[...vi(this),...uo.call(this)]},this.isAmbientLight2=!0,pn.upgradeLight.call(this)}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}}Hm([ae("Enabled"),tt("setDirty")],vl.prototype,"visible"),Hm([Fe("Name"),tt("setDirty")],vl.prototype,"name"),Hm([Tn("Color",r=>({onChange:()=>r.setDirty()}))],vl.prototype,"color"),Hm([Lt("Intensity"),tt("setDirty")],vl.prototype,"intensity");var hk=Object.defineProperty,vs=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&hk(e,t,n),n};const _n=class extends il{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Directional Light",children:[...vi(this),...uo.call(this)]},this.isDirectionalLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),pn.upgradeLight.call(this),this.shadowFrustum=10}_mapSizeChanged(){this.shadow.map?.dispose(),this.shadow.mapPass?.dispose(),this.shadow.map=null,this.shadow.mapPass=null,this.setDirty({change:"shadowMapSize"})}_shadowFrustumChanged(){const e=this.shadowFrustum;this.shadow.camera.left=-e/2,this.shadow.camera.right=e/2,this.shadow.camera.top=e/2,this.shadow.camera.bottom=-e/2,this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:"shadowFrustum"})}_shadowCamUpdate(e){this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:e})}autoScale(){console.warn("DirectionalLight2: AutoScale not supported on Lights")}autoCenter(){console.warn("DirectionalLight2: AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}};vs([ae("Enabled"),tt("setDirty")],_n.prototype,"visible"),vs([Fe("Name"),tt("setDirty")],_n.prototype,"name"),vs([Tn("Color",r=>({onChange:()=>r.setDirty()}))],_n.prototype,"color"),vs([Oe("Intensity",[0,100],.01),tt("setDirty")],_n.prototype,"intensity"),vs([gi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],_n.prototype,"position"),vs([gi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],_n.prototype,"rotation"),vs([ae("Cast Shadow"),tt("setDirty")],_n.prototype,"castShadow"),vs([gi("Shadow Map Size",void 0,void 0,r=>({onChange:()=>r._mapSizeChanged()})),Vt({obj:"shadow",key:"mapSize",onChange:_n.prototype._mapSizeChanged,onChangeParams:!1})],_n.prototype,"shadowMapSize"),vs([Oe("Shadow Bias",[-.001,.001],1e-5),Vt({obj:"shadow",key:"bias",onChange:"setDirty"})],_n.prototype,"shadowBias"),vs([Oe("Shadow Normal Bias",[-.1,.1],.005),Vt({obj:"shadow",key:"normalBias",onChange:"setDirty"})],_n.prototype,"shadowNormalBias"),vs([Oe("Shadow Radius",[0,5],.01),Vt({obj:"shadow",key:"radius",onChange:"setDirty"})],_n.prototype,"shadowRadius"),vs([Lt("Shadow Frustum"),ei(_n.prototype._shadowFrustumChanged)],_n.prototype,"shadowFrustum"),vs([Lt("Shadow Near"),Vt({obj:"shadow",key:["camera","near"],onChange:_n.prototype._shadowCamUpdate})],_n.prototype,"shadowNear"),vs([Lt("Shadow Far"),Vt({obj:"shadow",key:["camera","far"],onChange:_n.prototype._shadowCamUpdate})],_n.prototype,"shadowFar");let Qm=_n;var uk=Object.defineProperty,ih=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&uk(e,t,n),n};class Ca extends Dp{constructor(e,t,i){super(e,t,i),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Hemisphere Light",children:[...vi(this),...uo.call(this)]},this.isHemisphereLight2=!0,pn.upgradeLight.call(this)}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}}ih([ae("Enabled"),tt("setDirty")],Ca.prototype,"visible"),ih([Fe("Name"),tt("setDirty")],Ca.prototype,"name"),ih([Tn("Sky Color",r=>({onChange:()=>r.setDirty()}))],Ca.prototype,"color"),ih([Tn("Ground Color",r=>({onChange:()=>r.setDirty()}))],Ca.prototype,"groundColor"),ih([Lt("Intensity"),tt("setDirty")],Ca.prototype,"intensity"),ih([gi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Ca.prototype,"position");var dk=Object.defineProperty,Kn=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&dk(e,t,n),n};const Wi=class extends tl{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Point Light",children:[...vi(this),...uo.call(this)]},this.isPointLight2=!0,pn.upgradeLight.call(this)}_mapSizeChanged(){this.shadow.map?.dispose(),this.shadow.mapPass?.dispose(),this.shadow.map=null,this.shadow.mapPass=null,this.setDirty({change:"shadowMapSize"})}_shadowCamUpdate(e){this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:e})}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}};Kn([ae("Enabled"),tt("setDirty")],Wi.prototype,"visible"),Kn([Fe("Name"),tt("setDirty")],Wi.prototype,"name"),Kn([Tn("Color",r=>({onChange:()=>r.setDirty()}))],Wi.prototype,"color"),Kn([Lt("Intensity"),tt("setDirty")],Wi.prototype,"intensity"),Kn([Lt("Distance"),tt("setDirty")],Wi.prototype,"distance"),Kn([Lt("Decay"),tt("setDirty")],Wi.prototype,"decay"),Kn([Lt("Power"),tt("setDirty")],Wi.prototype,"power"),Kn([gi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Wi.prototype,"position"),Kn([ae("Cast Shadow"),tt("setDirty")],Wi.prototype,"castShadow"),Kn([gi("Shadow Map Size",void 0,void 0,r=>({onChange:()=>r._mapSizeChanged()})),Vt({obj:"shadow",key:"mapSize",onChange:Wi.prototype._mapSizeChanged,onChangeParams:!1})],Wi.prototype,"shadowMapSize"),Kn([Oe("Shadow Bias",[-.001,.001],1e-5),Vt({obj:"shadow",key:"bias",onChange:"setDirty"})],Wi.prototype,"shadowBias"),Kn([Oe("Shadow Radius",[0,5],.01),Vt({obj:"shadow",key:"radius",onChange:"setDirty"})],Wi.prototype,"shadowRadius"),Kn([Lt("Shadow Near"),Vt({obj:"shadow",key:["camera","near"],onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowNear"),Kn([Lt("Shadow Far"),Vt({obj:"shadow",key:["camera","far"],onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowFar"),Kn([Lt("Shadow Aspect"),Vt({obj:"shadow",key:"aspect",onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowAspect"),Kn([Oe("Shadow FOV",[1,179],1),Vt({obj:"shadow",key:"fov",onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowFov");let jm=Wi;var fk=Object.defineProperty,_l=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&fk(e,t,n),n};class Nr extends Bp{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"RectArea Light",children:[...vi(this),...uo.call(this)]},this.isRectAreaLight2=!0,pn.upgradeLight.call(this)}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}}_l([ae("Enabled"),tt("setDirty")],Nr.prototype,"visible"),_l([Fe("Name"),tt("setDirty")],Nr.prototype,"name"),_l([Tn("Color",r=>({onChange:()=>r.setDirty()}))],Nr.prototype,"color"),_l([Lt("Intensity"),tt("setDirty")],Nr.prototype,"intensity"),_l([Lt("Width"),tt("setDirty")],Nr.prototype,"width"),_l([Lt("Height"),tt("setDirty")],Nr.prototype,"height"),_l([Lt("Power"),tt("setDirty")],Nr.prototype,"power");var pk=Object.defineProperty,bn=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&pk(e,t,n),n};const Ci=class extends zc{constructor(e,t,i,n,s,a){super(e,t,i,n,s,a),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Spot Light",children:[...vi(this),...uo.call(this)]},this.isSpotLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),pn.upgradeLight.call(this)}_mapSizeChanged(){this.shadow.map?.dispose(),this.shadow.mapPass?.dispose(),this.shadow.map=null,this.shadow.mapPass=null,this.setDirty({change:"shadowMapSize"})}_shadowCamUpdate(e){this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:e})}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}};bn([ae("Enabled"),tt("setDirty")],Ci.prototype,"visible"),bn([Fe("Name"),tt("setDirty")],Ci.prototype,"name"),bn([Tn("Color",r=>({onChange:()=>r.setDirty()}))],Ci.prototype,"color"),bn([Lt("Intensity"),tt("setDirty")],Ci.prototype,"intensity"),bn([Oe("Angle",[0,2],.01),tt("setDirty")],Ci.prototype,"angle"),bn([Oe("Penumbra",[0,.9999],.01),tt("setDirty")],Ci.prototype,"penumbra"),bn([Fe("Distance"),tt("setDirty")],Ci.prototype,"distance"),bn([Fe("Decay"),tt("setDirty")],Ci.prototype,"decay"),bn([gi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Ci.prototype,"position"),bn([gi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Ci.prototype,"rotation"),bn([ae("Cast Shadow"),tt("setDirty")],Ci.prototype,"castShadow"),bn([gi("Shadow Map Size",void 0,void 0,r=>({onChange:()=>r._mapSizeChanged()})),Vt({obj:"shadow",key:"mapSize",onChange:Ci.prototype._mapSizeChanged,onChangeParams:!1})],Ci.prototype,"shadowMapSize"),bn([Oe("Shadow Bias",[-.001,.001],1e-5),Vt({obj:"shadow",key:"bias",onChange:"setDirty"})],Ci.prototype,"shadowBias"),bn([Oe("Shadow Radius",[0,5],.01),Vt({obj:"shadow",key:"radius",onChange:"setDirty"})],Ci.prototype,"shadowRadius"),bn([Oe("Shadow Focus",[0,1],.001),Vt({obj:"shadow",key:"focus",onChange:"setDirty"})],Ci.prototype,"shadowFocus"),bn([Lt("Shadow Near"),Vt({obj:"shadow",key:["camera","near"],onChange:Ci.prototype._shadowCamUpdate})],Ci.prototype,"shadowNear"),bn([Lt("Shadow Far"),Vt({obj:"shadow",key:["camera","far"],onChange:Ci.prototype._shadowCamUpdate})],Ci.prototype,"shadowFar"),bn([Lt("Shadow Aspect"),Vt({obj:"shadow",key:"aspect",onChange:Ci.prototype._shadowCamUpdate})],Ci.prototype,"shadowAspect"),bn([Oe("Shadow FOV",[1,179],1),Vt({obj:"shadow",key:"fov",onChange:Ci.prototype._shadowCamUpdate})],Ci.prototype,"shadowFov");let Wm=Ci;function bd(){this.assetType="texture",this.userData||(this.userData={}),this.appliedObjects||(this.appliedObjects=new Set),this.setDirty||(this.setDirty=()=>this.needsUpdate=!0)}function NM(r){return this.userData?.__isIWebGLRenderer?this:(this.userData||(this.userData={__isIWebGLRenderer:!0}),this.userData.__isIWebGLRenderer=!0,this.renderWithModes||(this.renderWithModes=kM),this.renderManager=r,this.baseRenderer||Object.defineProperty(this,"baseRenderer",{get:()=>(console.warn("IWebGLRenderer.baseRenderer is deprecated, use IWebGLRenderer.renderManager instead"),this.renderManager)}),this)}function kM(r,e){const t=this.userData,{backgroundRender:i,transparentRender:n,shadowMapRender:s,mainRenderPass:a,opaqueRender:o,transmissionRender:l,sceneRender:c,screenSpaceRendering:h}=t;r.backgroundRender!==void 0&&(t.backgroundRender=r.backgroundRender),r.transparentRender!==void 0&&(t.transparentRender=r.transparentRender),r.shadowMapRender!==void 0&&(t.shadowMapRender=r.shadowMapRender),r.mainRenderPass!==void 0&&(t.mainRenderPass=r.mainRenderPass),r.opaqueRender!==void 0&&(t.opaqueRender=r.opaqueRender),r.sceneRender!==void 0&&(t.sceneRender=r.sceneRender),r.transmissionRender!==void 0&&(t.transmissionRender=r.transmissionRender),r.screenSpaceRendering!==void 0&&(t.screenSpaceRendering=r.screenSpaceRendering),e(),t.backgroundRender=i,t.transparentRender=n,t.shadowMapRender=s,t.mainRenderPass=a,t.opaqueRender=o,t.sceneRender=c,t.transmissionRender=l,t.screenSpaceRendering=h}const mk=kM;var gk=Object.defineProperty,Ak=Object.getOwnPropertyDescriptor,kn=(r,e,t,i)=>{for(var n=i>1?void 0:i?Ak(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&gk(e,t,n),n};f.RootScene=class extends qa{constructor(e,t){super(),this.isRootScene=!0,this.assetType="model",this._mainCamera=null,this.backgroundColor=null,this.background=null,this.backgroundIntensity=1,this.backgroundTonemap=!0,this._environment=null,this.environmentIntensity=1,this.textureSlots={},this.fixedEnvMapDirection=!1,this.autoDisposeSceneMaps=!0,this._dummyCam=new th(""),this._mainCameraUpdate=i=>{this._mainCamera?.parent||this.setDirty({refreshScene:!1}),this.dispatchEvent({...i,type:"mainCameraUpdate"}),this.dispatchEvent({...i,type:"activeCameraUpdate"}),i.source!=="RootScene"&&(i.key==="fov"&&this.dollyActiveCameraFov()||this.refreshActiveCameraNearFar(!i.projectionUpdated))},this._sceneBounds=new In,this._sceneBoundingRadius=0,this.refreshUi=Ge.refreshUi.bind(this),this.traverseModels=Ge.traverseModels.bind(this),this._v1=new x,this._v2=new x,this._autoNearFarDisabled=new Set,this.overrideRenderEnvironment=null,this._isMainRendering=!1,this.setDirty=this.setDirty.bind(this),this.name="RootScene",this.objectProcessor=t,Ge.upgradeObject3D.call(this),this.objectProcessor?.processObject(this),this.addEventListener("materialUpdate",i=>this.dispatchEvent({...i,type:"sceneMaterialUpdate"})),this.addEventListener("objectUpdate",this.refreshScene),this.addEventListener("geometryUpdate",this.refreshScene),this.addEventListener("geometryChanged",this.refreshScene),this.environmentRotation?._onChange(()=>{this.setDirty({key:"environmentRotation",value:this.environmentRotation})}),this.backgroundRotation?._onChange(()=>{this.setDirty({key:"backgroundRotation",value:this.backgroundRotation})}),this.defaultCamera=e,this.modelRoot=new ft,this.modelRoot.userData.rootSceneModelRoot=!0,this.modelRoot.name="Scene",this.add(this.modelRoot),this.add(this.defaultCamera),this.mainCamera=this.defaultCamera,Object.defineProperty(this,"environment",{configurable:!0,enumerable:!0,get:()=>this._isMainRendering&&this.overrideRenderEnvironment!==null?this.overrideRenderEnvironment:this._environment,set:i=>{const n=this._environment;this._environment=i,this._onEnvironmentChange({key:"environment",value:i,oldValue:n,target:this})}})}get _backgroundColorUi(){return"#"+(this.backgroundColor?.getHexString()??"000000")}set _backgroundColorUi(e){this.setBackgroundColor(e)}toggleTransparentBackground(){this.backgroundColor?(this.background=null,this.backgroundColor=null):this.backgroundColor=new se(16777215),this.refreshUi?.(),this.setDirty()}toggleEnvironmentBackground(){this.background==="environment"?this.background=null:this.background="environment"}get mainCamera(){return this._mainCamera||this._dummyCam}set mainCamera(e){const t=this.mainCamera;e||(e=this.defaultCamera),t!==e&&(t&&(t.deactivateMain(void 0,!0),t.removeEventListener("cameraUpdate",this._mainCameraUpdate)),e?(this._mainCamera=e,e.addEventListener("cameraUpdate",this._mainCameraUpdate),e.activateMain(void 0,!0),!e._canvas&&e!==this.defaultCamera&&console.warn("RootScene: mainCamera does not have a canvas set, some controls might not work properly.")):this._mainCamera=null,this.dispatchEvent({type:"activeCameraChange",lastCamera:t,camera:e}),this.dispatchEvent({type:"mainCameraChange",lastCamera:t,camera:e}),this.setDirty())}get renderCamera(){return this._renderCamera??this.mainCamera}set renderCamera(e){const t=this._renderCamera;this._renderCamera=e,this.dispatchEvent({type:"renderCameraChange",lastCamera:t,camera:e})}addObject(e,t){return(t?.clearSceneObjects||t?.disposeSceneObjects)&&this.clearSceneModels(t.disposeSceneObjects),e&&(e.isObject3D?(this._addObject3D(e,t),this.dispatchEvent({type:"addSceneObject",object:e,options:t}),e):(console.error("Invalid object, cannot add to scene.",e),e))}loadModelRoot(e,t){if((t?.clearSceneObjects||t?.disposeSceneObjects)&&this.clearSceneModels(t.disposeSceneObjects),e.userData?.rootSceneModelRoot||console.error("RootScene: Invalid model root scene object. Trying to add anyway.",e),e.userData&&(e.userData.__importData&&(this.modelRoot.userData.__importData={...this.modelRoot.userData.__importData,...e.userData.__importData}),e.userData.gltfAsset&&(this.modelRoot.userData.gltfAsset={...this.modelRoot.userData.gltfAsset,...e.userData.gltfAsset,extras:{...this.modelRoot.userData.gltfAsset?.extras,...e.userData.gltfAsset.extras}}),e.userData.gltfExtras&&(this.modelRoot.userData.gltfExtras={...this.modelRoot.userData.gltfExtras,...e.userData.gltfExtras})),e.userData?.gltfAsset?.copyright&&e.children.forEach(n=>!n.userData.license&&(n.userData.license=e.userData.gltfAsset?.copyright)),e.animations){this.modelRoot.animations||(this.modelRoot.animations=[]);for(const n of e.animations)this.modelRoot.animations.includes(n)||this.modelRoot.animations.push(n)}return e._loadingPromise&&(this.modelRoot._loadingPromise?this.modelRoot._loadingPromise=Promise.allSettled([this.modelRoot._loadingPromise,e._loadingPromise]):this.modelRoot._loadingPromise=e._loadingPromise),(e._childrenCopy||[...e.children]).map(n=>this.addObject(n,{...t,clearSceneObjects:!1,disposeSceneObjects:!1}))}_addObject3D(e,{addToRoot:t=!1,...i}={}){const n=e;if(!n||!n.isObject3D){console.error("RootScene: Invalid object, cannot add to scene.");return}const s=t?this:this.modelRoot;if(s.add(n),i.indexInParent!==void 0){const a=i.indexInParent,o=s.children.indexOf(n);a>=0&&o>=0&&a!==o&&a<s.children.length&&(s.children.splice(o,1),s.children.splice(a,0,n))}uM(n,i),this.setDirty({refreshScene:!0})}centerAllGeometries(e=!0,t){return c0(t??this.modelRoot,e)}clearSceneModels(e=!1,t=!0){if(e)return this.disposeSceneModels(t);this.modelRoot.clear(),this.modelRoot.children=[],t&&this.setDirty({refreshScene:!0})}disposeSceneModels(e=!0,t=!0){if(t){for(const i of[...this.modelRoot.children])i.dispose?i.dispose():i.removeFromParent();this.modelRoot.clear(),e&&this.setDirty({refreshScene:!0})}else for(const i of this.modelRoot.children)i.dispose&&i.dispose(!1)}_onEnvironmentChange(e){e?.oldValue&&e.oldValue!==e.value&&this.autoDisposeSceneMaps&&typeof e.oldValue.dispose=="function"&&e.oldValue.dispose(),this.environment?.mapping===Kh&&(this.environment.mapping=Jr,this.environment.needsUpdate=!0),this.dispatchEvent({type:"environmentChanged",oldTexture:e?.oldValue?.isTexture?e.oldValue:null,texture:this.environment?.isTexture?this.environment:null,environment:this.environment}),this.setDirty({refreshScene:!0,geometryChanged:!1}),this.refreshUi?.()}onBackgroundChange(e){e?.oldValue&&e.oldValue!==e.value&&this.autoDisposeSceneMaps&&typeof e.oldValue.dispose=="function"&&e.oldValue.dispose(),this.dispatchEvent({type:"backgroundChanged",oldTexture:e?.oldValue&&e.oldValue.isTexture?e.oldValue:null,texture:this.background?.isTexture?this.background:null,background:this.background,backgroundColor:this.backgroundColor}),this.setDirty({refreshScene:!0,geometryChanged:!1}),this.refreshUi?.()}add(...e){const t=e.filter(i=>i.parent!==this);return t.length&&super.add(...t),this}setBackgroundColor(e){const t=e||typeof e=="number"?new se(e):null;(t&&this.backgroundColor&&!t.equals(this.backgroundColor)||(!t||!this.backgroundColor)&&t!==this.backgroundColor)&&(this.backgroundColor=t)}setDirty(e){return e?.sceneUpdate&&(console.warn("sceneUpdate is deprecated, use refreshScene instead."),e.refreshScene=!0),this.dispatchEvent({type:"update",bubbleToParent:!1,object:this}),Ge.setDirty.call(this,{...e,scene:this}),this}refreshScene(e){const t=e&&e.type==="objectUpdate"&&(e.object===this||e.target===this);return e?.sceneUpdate===!1||e?.refreshScene===!1||e?.object?.isCamera?t?this:this.setDirty(e):(this.refreshActiveCameraNearFar(),this._sceneBounds=this.getBounds(!1,!0),this._sceneBoundingRadius=this._sceneBounds.getSize(new x).length()/2,this.dispatchEvent({...e,type:"sceneUpdate",hierarchyChanged:["addedToParent","removedFromParent"].includes(e?.change||"")}),t||Ge.setDirty.call(this,{...e,scene:this}),this)}dispose(e=!0){this.disposeSceneModels(!1,e),e&&([...this.children].forEach(t=>t.dispose?t.dispose():t.removeFromParent()),this.clear()),this.disposeTextures(e)}disposeTextures(e=!0){this.environment?.dispose(),this.background?.isTexture&&this.background?.dispose?.(),e&&(this.environment=null,this.background=null)}getBounds(e=!1,t=!0,i=!0,n){return new In().expandByObject(this,e,t,s=>i&&(s.isWidget||s.assetType==="widget")?!0:n?.(s)??!1)}getModelBounds(e=!1,t=!0,i=!0,n){return this.modelRoot==null?new In:new In().expandByObject(this.modelRoot,e,t,s=>i&&s.assetType==="widget"?!0:n?.(s)??!1)}autoGPUInstanceMeshes(){const e=new Set;this.modelRoot.traverseModels(t=>{t.geometry&&e.add(t.geometry)},{visible:!1,widgets:!1}),e.forEach(t=>Iv(t))}disableAutoNearFar(e="default"){const t=this._autoNearFarDisabled.size===0;this._autoNearFarDisabled.add(e);const i=this.mainCamera;if(t&&i.userData.autoNearFar!==!1){let n=i.near,s=i.far;n=i.userData.minNearPlane??ct.defaultMinNear,s=i.userData.maxFarPlane??ct.defaultMaxFar,ct.setNearFar(i,n,s,!0,"RootScene")}}enableAutoNearFar(e="default"){if(!this._autoNearFarDisabled.has(e))return;this._autoNearFarDisabled.delete(e);const t=this.mainCamera;this._autoNearFarDisabled.size===0&&t&&this.setDirty()}refreshActiveCameraNearFar(e=!0){const t=this.mainCamera;if(!t)return!1;let i=t.near,n=t.far;if(t.userData.minNearPlane!==void 0&&(i=t.userData.minNearPlane),t.userData.maxFarPlane!==void 0&&(n=t.userData.maxFarPlane),this._autoNearFarDisabled.size!==0||t.userData.autoNearFar===!1)return ct.setNearFar(t,i,n,e,"RootScene");const s=this.getBounds(!1),a=s.getSize(this._v2).length();if(a<.001)return ct.setNearFar(t,i,n,e,"RootScene");t.getWorldPosition(this._v1).sub(s.getCenter(this._v2));const o=1.5*Math.max(.25,a)/2,l=this._v1.length(),c=Math.max(.1,-this._v1.normalize().dot(t.getWorldDirection(new x)));return i=Math.max(Math.max(t.userData.minNearPlane??ct.defaultMinNear,.001),c*(l-o)),n=Math.min(Math.max(i+o,c*(l+o)),t.userData.maxFarPlane??ct.defaultMaxFar),(n<i||n-i<.1)&&(n=i+.1),ct.setNearFar(t,i,n,e,"RootScene")}dollyActiveCameraFov(){const e=this.mainCamera;if(!e||!e.userData.dollyFov)return!1;const t=this.getModelBounds(!1,!0,!0),i=xm(e,t)*1.5,n=new x().subVectors(e.target,e.position).normalize();return e.position.copy(n.multiplyScalar(-i).add(e.target)),e.setDirty({change:"position",source:"RootScene"}),!0}updateShaderProperties(e){return e.uniforms.sceneBoundingRadius?e.uniforms.sceneBoundingRadius.value=this._sceneBoundingRadius:console.warn("RootScene: no uniform: sceneBoundingRadius"),this}toJSON(e){const t=ke.Serialize(this,e,!0);return t.envMapIntensity=t.environmentIntensity,t}fromJSON(e,t){const i=e.environment;return i!==void 0&&(this.environment=ke.Deserialize(i,this.environment,t,!1),delete e.environment,t?._configMetadata&&t._configMetadata.version<2&&this.environment?.rotation&&(this.environmentRotation.y=this.environment.rotation,this.environment.rotation=0)),e.environmentIntensity!==void 0&&e.envMapIntensity!==void 0&&(e={...e},delete e.envMapIntensity),ke.Deserialize(e,this,t,!0),e.environment=i,this}addEventListener(e,t){e==="activeCameraChange"&&console.error("activeCameraChange is deprecated. Use mainCameraChange instead."),e==="activeCameraUpdate"&&console.error("activeCameraUpdate is deprecated. Use mainCameraUpdate instead."),e==="sceneMaterialUpdate"&&console.error("sceneMaterialUpdate is deprecated. Use materialUpdate instead."),e==="update"&&console.error("update is deprecated. Use sceneUpdate instead."),super.addEventListener(e,t)}findObjectsByName(e,t,i=!1){const n=[],s=o=>{o.name===e&&n.push(o)},a=t??this;return i&&a.traverseModels?a.traverseModels(s,{visible:!1,widgets:!0}):a.traverse(s),n}resetCamera(e=void 0,t=new x(1,1,1),i=new x(0,0,0)){if(this._mainCamera){this.matrixWorldNeedsUpdate=!0,this.updateMatrixWorld(!0);const n=e?new In().expandByObject(e,!0,!0):this.getBounds(!0),s=n.getCenter(new x),a=n.getSize(new x).length()*.5;s.add(i.clone().multiplyScalar(a)),this._mainCamera.position=new x(s.x+t.x*a,s.y+t.y*a,s.z+t.z*a),this._mainCamera.target=s,this.setDirty()}}get minNearDistance(){return console.error("minNearDistance is deprecated. Use camera.userData.minNearPlane instead"),this.mainCamera.userData.minNearPlane??.02}set minNearDistance(e){console.error("minNearDistance is deprecated. Use camera.userData.minNearPlane instead"),this.mainCamera&&(this.mainCamera.userData.minNearPlane=e)}get activeCamera(){return console.error("activeCamera is deprecated. Use mainCamera instead."),this.mainCamera}set activeCamera(e){console.error("activeCamera is deprecated. Use mainCamera instead."),this.mainCamera=e}get modelObject(){return this}addSceneObject(e,t){return this.addObject(e,t)}updateScene(e){return console.warn("updateScene is deprecated. Use refreshScene instead"),this.refreshScene(e||{})}removeSceneModels(){this.clearSceneModels()}get autoNearFarEnabled(){return this._autoNearFarDisabled.size===0}set autoNearFarEnabled(e){e?this.enableAutoNearFar("default"):this.disableAutoNearFar("default")}get envMapIntensity(){return console.warn("RootScene.envMapIntensity is deprecated, use environmentIntensity instead."),this.environmentIntensity}set envMapIntensity(e){console.warn("RootScene.envMapIntensity is deprecated, use environmentIntensity instead."),this.environmentIntensity=e}},kn([z(),ei(f.RootScene.prototype.onBackgroundChange)],f.RootScene.prototype,"backgroundColor",2),kn([Tn("Background Color",r=>({hidden:()=>r.backgroundColor===null||r.backgroundColor===void 0||r.background==="environment"}))],f.RootScene.prototype,"_backgroundColorUi",1),kn([tt(f.RootScene.prototype.onBackgroundChange),z(),Dr("Background Image",r=>({hidden:()=>r.backgroundColor===null||r.backgroundColor===void 0||r.background==="environment"}))],f.RootScene.prototype,"background",2),kn([lt(void 0,r=>({label:()=>r.backgroundColor?"Set Transparent BG":"Set Color Background",tags:["context-menu"]}))],f.RootScene.prototype,"toggleTransparentBackground",1),kn([lt(void 0,r=>({label:()=>r.background==="environment"?"Remove Env Background":"Set Env Background",disabled:()=>!r.environment,tags:["context-menu"]}))],f.RootScene.prototype,"toggleEnvironmentBackground",1),kn([z(),tt(f.RootScene.prototype.setDirty),Oe("Background Intensity",[0,10],.01)],f.RootScene.prototype,"backgroundIntensity",2),kn([ae("Background Tonemap"),tt(f.RootScene.prototype.setDirty),z()],f.RootScene.prototype,"backgroundTonemap",2),kn([Dr("Environment"),z()],f.RootScene.prototype,"environment",2),kn([Oe("Environment Intensity",[0,10],.01),z(),tt(f.RootScene.prototype.setDirty)],f.RootScene.prototype,"environmentIntensity",2),kn([z(),gi("Environment Rotation",void 0,void 0,r=>({disabled:()=>r.fixedEnvMapDirection||!r.environment}))],f.RootScene.prototype,"environmentRotation",2),kn([z(),gi("Background Rotation",void 0,void 0,r=>({hidden:()=>!r.background||r.background==="environment"||!r.background.isTexture||r.background.mapping!==Jr}))],f.RootScene.prototype,"backgroundRotation",2),kn([z()],f.RootScene.prototype,"textureSlots",2),kn([ae("Fixed Env Direction"),z(),tt(f.RootScene.prototype.setDirty)],f.RootScene.prototype,"fixedEnvMapDirection",2),kn([Li(),z()],f.RootScene.prototype,"defaultCamera",2),kn([lt("Center All Geometries",{sendArgs:!1,tags:["context-menu"]})],f.RootScene.prototype,"centerAllGeometries",1),kn([lt("Auto GPU Instance Meshes",{tags:["context-menu"]})],f.RootScene.prototype,"autoGPUInstanceMeshes",1),f.RootScene=kn([gt("Root Scene")],f.RootScene);class wd{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const yk=new Mr(-1,1,1,-1,0,1);class vk extends $e{constructor(){super(),this.setAttribute("position",new Me([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Me([0,2,0,0,2,0],2))}}const _k=new vk;class GM{constructor(e){this._mesh=new ye(_k,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,yk)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class p0 extends wd{constructor(e,t,i=null,n=null,s=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=i,this.clearColor=n,this.clearAlpha=s,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new se}render(e,t,i,n,s,a){if(!this.scene||!this.camera)return;const o=e.autoClear;e.autoClear=!1;let l,c;if(this.overrideMaterial!==null&&(c=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor)),this.clearAlpha!==null&&(l=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:i),a){const h=e.getContext();h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.RENDERBUFFER,a)}if(this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),a){const h=e.getContext();h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.RENDERBUFFER,null)}this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(l),this.overrideMaterial!==null&&(this.scene.overrideMaterial=c),e.autoClear=o}}const bl={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform float opacity;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = opacity * texel;


		}`};class m0 extends wd{constructor(e,t){super(),this.textureID=t!==void 0?t:"tDiffuse",e instanceof nn?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=ko.clone(e.uniforms),this.material=new nn({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new GM(this.material),this.useExistingRenderTarget=!1}render(e,t,i){this.uniforms[this.textureID]&&i&&(this.uniforms[this.textureID].value=i.texture),this.fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(this.useExistingRenderTarget||e.setRenderTarget(t||null),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}}var bk=Object.defineProperty,wk=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&bk(e,t,n),n};const g0=(Fl=class extends m0{constructor(e,...t){super(e.isMaterial?e:new RM(e,t),t.length<1?Fl.DEFAULT_TEX_ID:t[0]),this.overrideReadBuffer=null,this.isExtendedShaderPass=!0,this.enabled=!0,this.onDirty=[],this.setDirty=this.setDirty.bind(this)}render(e,t,i,n,s){this.enabled&&e.renderWithModes({backgroundRender:!1},()=>{super.render(e,t||null,this.overrideReadBuffer||i,n,s)})}updateShaderProperties(e){e&&(Array.isArray(e)||(e=[e]),e.forEach(t=>t?.updateShaderProperties(this.material)))}dispose(){this.material?.dispose?.(),this.fsQuad?.dispose?.(),this.onDirty=[]}setDirty(){this.material&&(this.material.needsUpdate=!0),this.onDirty?.forEach(e=>e())}get isShaderPass2(){return console.error("isShaderPass2 is deprecated, use isExtendedShaderPass instead"),!0}},Fl.DEFAULT_TEX_ID="tDiffuse",Fl);wk([ae("Enabled"),z(),ei(g0.prototype.setDirty)],g0.prototype,"enabled");let nh=g0;class zM extends nh{constructor(e,t="c = a + b;",i="",n,s=120){super({vertexShader:bl.vertexShader,fragmentShader:`
                varying vec2 vUv;
                ${i}
                void main() {
                    vec4 a = tDiffuseTexelToLinear ( texture2D( tDiffuse, vUv ) );
                    vec4 b = tDiffuse2TexelToLinear ( texture2D( tDiffuse2, vUv ) );
                    vec4 c = vec4(0);
                    ${t}
                    c = clamp(c, vec4(0), vec4(MAX_INTENSITY));
                    gl_FragColor = c;
                    #include <colorspace_fragment>
                }
            `,uniforms:{tDiffuse:{value:null},tDiffuse2:{value:n},...e},defines:{MAX_INTENSITY:s}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var Ck=Object.defineProperty,xk=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Ck(e,t,n),n};class A0 extends p0{constructor(e,t,i=new se(0,0,0),n=0){super(void 0,void 0,t,i,n),this.isExtendedRenderPass=!0,this.enabled=!0,this.passId="render",this._doTransmissionFix=!0,this.blurTransmissionTarget=!0,this.preserveTransparentTarget=!1,this.preserveOpaqueTarget=!1,this.renderBackground=!0,this.onDirty=[],this.uiConfig={label:"Render Pass",type:"folder",children:vi(this)},this.renderManager=e,this._blendPass=new zM({},"c = vec4(a.rgb * (1. - b.a) + b.rgb * b.a, 1.);","",void 0,e.maxHDRIntensity),this.setDirty=this.setDirty.bind(this)}get transparentTarget(){if(!this._transparentTarget){const e=this.renderManager.msaa;this._transparentTarget=this.renderManager.getTempTarget({sizeMultiplier:1,samples:e?typeof e!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:e:0,stencilBuffer:this.renderManager.composerTarget.stencilBuffer,colorSpace:si,type:this.renderManager.renderer.extensions.has("EXT_color_buffer_half_float")?$t:Wt,format:Kt,minFilter:st,magFilter:st,depthBuffer:!1})}return this._transparentTarget}_releaseTransparentTarget(){this._transparentTarget&&this.renderManager.releaseTempTarget(this._transparentTarget),this._transparentTarget=void 0}get opaqueTarget(){if(!this._opaqueTarget){const e=this.renderManager.composerTarget,t=this.renderManager.msaa;this._opaqueTarget=this.renderManager.getTempTarget({sizeMultiplier:1,samples:t?typeof t!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:t:0,stencilBuffer:this.renderManager.composerTarget.stencilBuffer,colorSpace:e.texture.colorSpace,type:this.renderManager.rgbm?Wt:$t,format:e.texture.format,minFilter:e.texture.minFilter,magFilter:e.texture.magFilter,depthBuffer:e.depthBuffer,generateMipmaps:e.texture.generateMipmaps})}return this._opaqueTarget}_releaseOpaqueTarget(){this._opaqueTarget&&this.renderManager.releaseTempTarget(this._opaqueTarget),this._opaqueTarget=void 0}render(e,t,i,n,s){if(!this.enabled)return;let a=!1;if(e.userData.mainRenderPass=!0,!this._doTransmissionFix&&!this.renderManager.rgbm){super.render(e,t||null,i,n,s),this.needsSwap=a,e.userData.mainRenderPass=void 0;return}const o=e.userData;o||console.error("threejs is not patched. Use the @repalash/three.js-modded to this functionality.");const l=(this.renderManager.zPrepass||!this.renderManager.depthBuffer)&&this.renderManager.gbufferTarget;let c;if(l){const d=this.renderManager.gbufferTarget;if(d){const p=e.properties.get(d);c=p.__webglDepthRenderbuffer||p.__webglDepthbuffer}c||console.warn("No depth/gbuffer present for zPrepass.")}const h=i;i=this.renderManager.msaa?this.opaqueTarget:i;let u=()=>{super.render(e,null,i,n,s,c)};if(this.renderManager.rgbm){if(this.renderManager.rgbm){a=!1;const d=this.renderToScreen;if(d&&!t&&console.error("ExtendedRenderPass: renderToScreen is true but writeBuffer is not set, which is required for rgbm"),this.renderToScreen=!1,e.info&&!e.info.autoReset)throw"renderer.info.autoReset must be true";{const p=e.autoClearDepth;e.autoClearDepth=!l,e.renderWithModes({shadowMapRender:!0,backgroundRender:this.renderBackground,opaqueRender:!0,transparentRender:!1,transmissionRender:!1},u),e.autoClearDepth=p}if(!l&&i){const p=e.properties.get(i);c=p.__webglDepthRenderbuffer||p.__webglDepthbuffer}u=()=>{super.render(e,null,this.transparentTarget,n,s,c)};{const p=this.clear,m=e.autoClearDepth;e.autoClearDepth=!1,this.clear=!0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!0,transmissionRender:!1},u),this.clear=p,e.autoClearDepth=m}(!e.info||e.info.render.calls>0)&&(this._blendPass.uniforms.tDiffuse2.value=this.transparentTarget.texture,this._blendPass.render(e,t,i,n,s),a=!0);{const p=this.clear;this.clear=!1,o.transmissionRenderTarget=a?t:i,o.blurTransmissionTarget=this.blurTransmissionTarget&&o.transmissionRenderTarget.samples===0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!1,transmissionRender:!0},u),o.blurTransmissionTarget=void 0,o.transmissionRenderTarget=void 0,this.clear=p}if((!e.info||e.info.render.calls>0)&&(this._blendPass.uniforms.tDiffuse2.value=this.transparentTarget.texture,this._blendPass.render(e,t,i,n,s),a=!0),d){this.renderToScreen=!0;const p=a?t?.texture:i?.texture,m=Array.isArray(p)?p[0]:p;m&&this.renderManager.blit(void 0,{source:m,respectColorSpace:!0})}}}else{{const d=this.clear,p=e.autoClearDepth;e.autoClearDepth=!l,this.clear=!0,e.renderWithModes({shadowMapRender:!0,backgroundRender:this.renderBackground,opaqueRender:!0,transparentRender:!0,transmissionRender:!1},u),this.clear=d,e.autoClearDepth=p}{const d=i?i.texture:void 0;this.renderManager.blit(t,{clear:!0,source:d});const p=this.clear;this.clear=!1,o.transmissionRenderTarget=t,o.blurTransmissionTarget=this.blurTransmissionTarget&&o.transmissionRenderTarget.samples===0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!1,transmissionRender:!0},u),o.blurTransmissionTarget=void 0,o.transmissionRenderTarget=void 0,this.clear=p}a=!1}if(!a&&h!==i&&i){const d=Array.isArray(i.texture)?i.texture[0]:i.texture;d&&this.renderManager.blit(h,{source:d,clear:!0}),i=h}this.preserveTransparentTarget||this._releaseTransparentTarget(),this.preserveOpaqueTarget||this._releaseOpaqueTarget(),this.needsSwap=a,e.userData.mainRenderPass=void 0}dispose(){this._releaseTransparentTarget(),this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach(e=>e())}beforeRender(e,t,i){this.scene=e,this.camera=t}get isRenderPass2(){return console.error("isRenderPass2 is deprecated, use isExtendedRenderPass instead"),!0}}xk([ae("Enabled"),z()],A0.prototype,"enabled");class y0 extends nh{constructor(e,t=!0){super({uniforms:ko.clone(bl.uniforms),vertexShader:bl.vertexShader,fragmentShader:ma`
                uniform float opacity;
                #include <alphatest_pars_fragment>
                varying vec2 vUv;
                void main() {
                    ${t?"vec4 diffuseColor = tDiffuseTexelToLinear(texture2D(tDiffuse, vUv)) * opacity;":"vec4 diffuseColor = texture2D(tDiffuse, vUv) * opacity;"}
                    #include <alphatest_fragment>
                    ${e?it(e,"diffuseColor"):""}
                    #ifdef OPAQUE
                    diffuseColor.a = 1.0;
                    #endif
                    gl_FragColor = diffuseColor;
                    ${t?"#include <colorspace_fragment>":""}
                }
            `},"tDiffuse")}}var Sk=Object.defineProperty,Ek=Object.getOwnPropertyDescriptor,VM=(r,e,t,i)=>{for(var n=i>1?void 0:i?Ek(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Sk(e,t,n),n};f.GBufferRenderPass=class extends p0{constructor(e,t,i,n=new se(1,1,1),s=1){super(void 0,void 0,i,n,s),this.passId=e,this.target=t,this.isGBufferRenderPass=!0,this.enabled=!0,this._transparentMats=new Set,this._transmissiveMats=new Set,this.preprocessMaterial=(a,o)=>{o=o??a.userData.renderToGBuffer,a.userData.pluginsDisabled&&(o=!1),(a.transparent&&(o||a.opacity>.99&&!a.map&&!a.alphaMap)||!a.transparent&&!a.transmission&&o===!1)&&(this._transparentMats.add(a),a.transparent=!a.transparent),a.transmission&&Math.abs(a.transmission||0)>0&&o&&(this._transmissiveMats.add([a,a.transmission]),a.transmission=0)},this.preprocessObject=a=>{if(a.customDepthMaterial){const o=a.customDepthMaterial;o.allowOverride=!1;const l=a.material;a.forcedOverrideMaterial=o;const c=Array.isArray(l)?l[0]:l;return c&&(o.userData.renderToGBuffer=c.userData.renderToGBuffer,o.userData.renderToDepth=c.userData.renderToDepth,o.userData.pluginsDisabled=c.userData.pluginsDisabled,o.side=c.side),o}return a.material},this.postprocessObject=a=>{a.customDepthMaterial&&delete a.forcedOverrideMaterial}}render(e,t,i,n,s){if(!this.scene||!this.camera)return;const a=e.getRenderTarget(),o=e.getActiveCubeFace(),l=e.getActiveMipmapLevel(),c=new Set;this.scene.traverse(h=>{if(!h.visible)return;c.add(h);const u=this.preprocessObject(h);u&&(Array.isArray(u)?u.forEach(d=>this.preprocessMaterial(d)):this.preprocessMaterial(u))}),e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!1,transmissionRender:!1,mainRenderPass:!1},()=>super.render(e,null,it(this.target),n,s)),this._transparentMats.forEach(h=>h.transparent=!h.transparent),this._transparentMats.clear(),this._transmissiveMats.forEach(([h,u])=>h.transmission=u),this._transmissiveMats.clear(),e.setRenderTarget(a,o,l),c.forEach(h=>this.postprocessObject(h))}beforeRender(e,t,i){this.scene=e,this.camera=t}},VM([ae("Enabled")],f.GBufferRenderPass.prototype,"enabled",2),f.GBufferRenderPass=VM([gt(r=>r.passId+" Render Pass")],f.GBufferRenderPass);const Mk=`#include <packing>
varying vec2 vUv;
#include <alphatest_pars_fragment>
void main(){vec4 diffuseColor=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));
#ifdef HAS_TRANSPARENT_TARGET
vec4 transparentColor=tTransparentTexelToLinear(texture2D(tTransparent,vUv));
#else
vec4 transparentColor=vec4(0.0);
#endif
#ifdef HAS_GBUFFER
float depth=getDepth(vUv);bool isBackground=depth>0.99&&transparentColor.a<0.001;
#endif
#glMarker
#ifdef HAS_GBUFFER
#if (defined(CLIP_BACKGROUND) && CLIP_BACKGROUND > 0) || defined(CLIP_BACKGROUND_FORCE)
if(isBackground)diffuseColor.a=0.0;if(depth>0.99&&transparentColor.a>=0.001)diffuseColor.a=transparentColor.a;
#endif
if(depth<0.00001)diffuseColor.a=0.0;
#endif
#include <alphatest_fragment>
#ifdef OPAQUE
diffuseColor.a=1.0;
#endif
gl_FragColor=diffuseColor;
#include <colorspace_fragment>
}`;var Tk=Object.defineProperty,Ik=Object.getOwnPropertyDescriptor,qm=(r,e,t,i)=>{for(var n=i>1?void 0:i?Ik(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Tk(e,t,n),n};f.ScreenPass=class extends nh{constructor(e="",...t){super(e?.fragmentShader||e?.isShaderMaterial?e:Pk(e),...t.length?t:["tDiffuse","tTransparent"]),this.passId="screen",this.after=["render"],this.required=["render"],this.outputColorSpace=vt,this._needsReRender=!1,this.clipBackgroundForce=!1,this.clipBackground=!1,this.material.addEventListener("materialUpdate",this.setDirty)}render(e,t,i,n,s){const a=e.outputColorSpace;(!t||this.renderToScreen)&&(e.outputColorSpace=this.outputColorSpace),super.render(e,t,i,n,s),this._lastReadBuffer=i,e.outputColorSpace=a,this._needsReRender=!1}reRender(e,t,i,n){this._lastReadBuffer&&this.render(e,t,this._lastReadBuffer,i,n)}onPostFrame(e){this._needsReRender&&(this._needsReRender=!1,this.reRender(e.renderer),this.clipBackground&&!e.gbufferTarget&&console.warn("ScreenPass: clipBackground set to true but no gbufferTarget set. Try adding GBufferPlugin."))}dispose(){this._lastReadBuffer=void 0,super.dispose()}beforeRender(e,t,i){this.material.uniforms.tTransparent&&(this.material.uniforms.tTransparent.value=i.renderPass.preserveTransparentTarget&&i.renderPass.transparentTarget?.texture||null,this.material.defines.HAS_TRANSPARENT_TARGET=this.material.uniforms.tTransparent.value?1:void 0,this.material.defines.HAS_TRANSPARENT_TARGET||delete this.material.defines.HAS_TRANSPARENT_TARGET)}setDirty(){super.setDirty(),this._needsReRender=!0}},qm([Oi("Output Color Space",Mv.ColorSpace.uiConfig,r=>({onChange:r.setDirty}))],f.ScreenPass.prototype,"outputColorSpace",2),qm([um("CLIP_BACKGROUND_FORCE",void 0,void 0,f.ScreenPass.prototype.setDirty,!0)],f.ScreenPass.prototype,"clipBackgroundForce",2),qm([um("CLIP_BACKGROUND",void 0,void 0,f.ScreenPass.prototype.setDirty),ae()],f.ScreenPass.prototype,"clipBackground",2),f.ScreenPass=qm([gt("Screen Pass")],f.ScreenPass);function Pk(r){const e=At(Mk,"void main()",(Array.isArray(r)?r[0]:r?.pars||"")+`
`,{prepend:!0}),t=e.includes("#glMarker")?At(e,"#glMarker",(Array.isArray(r)?r[1]:typeof r=="string"?r:r?.main||"")+`
`,{prepend:!0}):e;return{...bl,fragmentShader:t,uniforms:{tDiffuse:{value:null},tTransparent:{value:null}},transparent:!0,blending:gn,side:fs}}function HM(r){const e=[],t={};for(const i of r)i.passId&&(t[i.passId]={after:i.after??[],before:i.before??[],dependencies:new Set(i.required??[])});for(const[i,n]of Object.entries(t)){const s=new Set([...n.after,...n.before]);n.dependencies.forEach(a=>s.has(a)&&s.delete(a)),s.forEach(a=>{const o=t[a];if(o){if(o.dependencies.has(i))throw console.error("cyclic",i,a),"Encountered cyclic dependency when sorting passes";n.dependencies.add(a)}})}for(;;){let i=!1;const n=[...Object.entries(t)];for(const[s,a]of n)if(!e.includes(s)&&Kx(e,a.dependencies.values())){const o=Math.max(-1,...a.after.map(c=>e.indexOf(c))),l=Math.min(e.length,...a.before.map(c=>{const h=e.indexOf(c);return h<0?e.length:h}));if(o>=l)throw console.error(a,r,e,o,l),"Unknown error when sorting passes";e.splice(a.after.length>0?o+1:l,0,s),i=!0,delete t[s]}if(Object.keys(t).length<1)break;if(!i)throw console.error(n,t,e),"Required pass dependency removed unexpectedly"}return e}class QM extends wd{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,i){const n=e.getContext(),s=e.state;s.buffers.color.setMask(!1),s.buffers.depth.setMask(!1),s.buffers.color.setLocked(!0),s.buffers.depth.setLocked(!0);let a,o;this.inverse?(a=0,o=1):(a=1,o=0),s.buffers.stencil.setTest(!0),s.buffers.stencil.setOp(n.REPLACE,n.REPLACE,n.REPLACE),s.buffers.stencil.setFunc(n.ALWAYS,a,4294967295),s.buffers.stencil.setClear(o),s.buffers.stencil.setLocked(!0),e.setRenderTarget(i),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),s.buffers.color.setLocked(!1),s.buffers.depth.setLocked(!1),s.buffers.color.setMask(!0),s.buffers.depth.setMask(!0),s.buffers.stencil.setLocked(!1),s.buffers.stencil.setFunc(n.EQUAL,1,4294967295),s.buffers.stencil.setOp(n.KEEP,n.KEEP,n.KEEP),s.buffers.stencil.setLocked(!0)}}class Dk extends wd{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class jM{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const i=e.getSize(new $);this._width=i.width,this._height=i.height,t=new ps(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:$t}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new m0(bl),this.copyPass.material.blending=gn,this.clock=new Lu}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){e===void 0&&(e=this.clock.getDelta());const t=this.renderer.getRenderTarget();let i=!1;for(let n=0,s=this.passes.length;n<s;n++){const a=this.passes[n];if(a.enabled!==!1){if(a.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(n),a.render(this.renderer,this.writeBuffer,this.readBuffer,e,i),a.needsSwap){if(i){const o=this.renderer.getContext(),l=this.renderer.state.buffers.stencil;l.setFunc(o.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),l.setFunc(o.EQUAL,1,4294967295)}this.swapBuffers()}QM!==void 0&&(a instanceof QM?i=!0:a instanceof Dk&&(i=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){const t=this.renderer.getSize(new $);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const i=this._width*this._pixelRatio,n=this._height*this._pixelRatio;this.renderTarget1.setSize(i,n),this.renderTarget2.setSize(i,n);for(let s=0;s<this.passes.length;s++)this.passes[s].setSize(i,n)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class WM extends jM{constructor(e,t){super(e,t),this.copyPass2=new y0}setPixelRatio(e,t=!0){const i=this.setSize;t||(this.setSize=()=>{}),super.setPixelRatio(e),t||(this.setSize=i)}}function qM(r={}){return[r.sizeMultiplier,r.samples,r.colorSpace,r.type,r.format,r.depthBuffer,r.depthTexture,r.textureCount,r.size?.width,r.size?.height].join(";")}class XM extends wi{constructor(){super(),this._trackedTargets=[],this._trackedTempTargets=[],this._releasedTempTargets={},this.maxTempPerKey=5,this._processNewTarget=this._processNewTarget.bind(this),this._processNewTempTarget=this._processNewTempTarget.bind(this),this.trackTarget=this.trackTarget.bind(this),this.disposeTarget=this.disposeTarget.bind(this),this.createTarget=this.createTarget.bind(this),this.createTargetCustom=this.createTargetCustom.bind(this)}trackTarget(e){this._trackedTargets.push(e)}removeTrackedTarget(e){const t=this._trackedTargets.indexOf(e);t>=0&&this._trackedTargets.splice(t,1)}createTarget({sizeMultiplier:e=void 0,samples:t=0,colorSpace:i=si,type:n=Wt,format:s=Kt,stencilBuffer:a=!1,depthBuffer:o=!0,depthTexture:l=!1,depthTextureType:c=ea,depthTextureFormat:h=Do,size:u=void 0,textureCount:d=1,...p}={},m=!0){this.isWebGL2||(t=0),e!==void 0&&u!==void 0&&console.error("Both sizeMultiplier and size are defined. sizeMultiplier will be ignored."),u=u||this.renderSize.clone().multiplyScalar(this.renderScale*(e=e||1)),u.width=Math.floor(u.width),u.height=Math.floor(u.height);const A=l?new jf(u.width,u.height,c):null;A&&(A.format=h);const g=this.createTargetCustom(u,{samples:t,colorSpace:i,type:n,format:s,depthBuffer:o,count:d,depthTexture:A,stencilBuffer:a});return this._processNewTarget(g,e,m),this._setTargetOptions(g,p),g}disposeTarget(e,t=!0){if(e){if(e.isTemporary)return this.releaseTempTarget(e);t&&this.removeTrackedTarget(e),e.dispose(!1)}}getTempTarget(e={}){const t=qM(e);let i;return this._releasedTempTargets[t]?.length&&(i=this._releasedTempTargets[t].pop()),i?this._setTargetOptions(i,e):(i=this.createTarget(e),this._processNewTempTarget(i,t)),i}releaseTempTarget(e){const t=e.targetKey;if(!t||!e.isTemporary)throw"Not a temp target";this._releasedTempTargets[t].length>this.maxTempPerKey?(this.removeTrackedTarget(e),e.dispose()):this._releasedTempTargets[t].push(e)}createTargetCustom({width:e,height:t},i={},n){let s=[e,t];if(n?.prototype===qA.prototype){if(e!==t)throw"Width and height of cube render target must be equal";s=[e]}return this._createTargetClass(n??ps,s,{format:Kt,minFilter:st,magFilter:st,generateMipmaps:!1,type:Wt,colorSpace:si,...i})}dispose(e=!0){this._trackedTargets.forEach(t=>t.dispose()),Object.values(this._trackedTempTargets).forEach(t=>t.dispose()),e&&(this._trackedTargets=[],this._releasedTempTargets={},this._trackedTempTargets=[])}resizeTrackedTargets(){for(const e of this._trackedTargets)this.resizeTrackedTarget(e)}resizeTrackedTarget(e){const t=e.sizeMultiplier;if(t){const i=this.renderSize.clone().multiplyScalar(this.renderScale*t);e.setSize(Math.floor(i.width),Math.floor(i.height))}}_processNewTempTarget(e,t){return e.isTemporary=!0,e.targetKey=t,this._releasedTempTargets[t]===void 0&&(this._releasedTempTargets[t]=[]),this._trackedTempTargets.push(e),e}_setTargetOptions(e,t){const i=e.texture;for(const n of Array.isArray(i)?i:[i])this._setTargetTextureOptions(n,t)}_setTargetTextureOptions(e,t){e.minFilter=t.minFilter??st,e.magFilter=t.magFilter??st,e.wrapS=t.wrapS??ui,e.wrapT=t.wrapT??ui,e.generateMipmaps=t.generateMipmaps??!1,e.generateMipmaps&&e.minFilter===st&&(e.minFilter=Nb),!e.generateMipmaps&&e.minFilter===Nb&&(e.minFilter=st)}_processNewTarget(e,t,i){return t!==void 0&&(e.sizeMultiplier=t),i&&this.trackTarget(e),e}}class qi{constructor(e,t,i,n,s){this.extensions=[],this.cls=e,this.ext=t,this.mime=i.filter(Boolean).map(a=>a.toLowerCase()),this.root=n,this.onCtor=s}ctor(e){const t=this.cls&&new this.cls(e.loadingManager);return typeof this.onCtor=="function"?this.onCtor(t,e,this):t}}const jr=class jr extends wi{constructor(e=!1,{simpleCache:t=!1,storage:i}={}){super(),this._logger=console.log,this._loaderCache=[],this._fileDatabase=new Map,this._cachedAssets=[],this.cacheImportedAssets=!0,this.importers=[new qi(Zt,["txt"],["text/plain"],!1)],this.autoSetName=!0,this._urlModifiers=[],e||(this._logger=()=>{}),this._onLoad=this._onLoad.bind(this),this._onProgress=this._onProgress.bind(this),this._onError=this._onError.bind(this),this._onStart=this._onStart.bind(this),this._urlModifier=this._urlModifier.bind(this),this._loadingManager=new Pp(this._onLoad,this._onProgress,this._onError),this._loadingManager.onStart=this._onStart;const n=this._loadingManager.itemStart;this._loadingManager.itemStart=l=>{this.dispatchEvent({type:"importFile",path:l,state:"downloading",progress:0}),n.call(this._loadingManager,l)};let s=[];const a=this._loadingManager.itemEnd;this._loadingManager.itemEnd=l=>{if(s.includes(l)){s=s.filter(c=>c!==l),a.call(this._loadingManager,l);return}this.dispatchEvent({type:"importFile",path:l,state:"downloading",progress:1}),a.call(this._loadingManager,l),this.dispatchEvent({type:"importFile",path:l,state:"done"})};const o=this._loadingManager.itemError;this._loadingManager.itemError=l=>{s.push(l),this.dispatchEvent({type:"importFile",path:l,state:"error"}),o.call(this._loadingManager,l)},this._loadingManager.setURLModifier(this._urlModifier),this._initCacheStorage(t,i??!0)}get storage(){return this._storage}get loadingManager(){return this._loadingManager}get cachedAssets(){return this._cachedAssets}addImporter(...e){for(const t of e){if(this.importers.includes(t)){console.warn("AssetImporter: Importer already added",t);return}this.importers.push(t)}}removeImporter(...e){for(const t of e){const i=this.importers.indexOf(t);i>=0&&this.importers.splice(i,1)}}async import(e,t,i,n){return e?Array.isArray(e)?(await Promise.all(e.map(async s=>this.import(s,t,i,n)))).flat(1):e instanceof File?await this.importFile(e,t,i):typeof e=="object"?await this.importAsset(e,t,i,n):typeof e=="string"?await this.importPath(e,t,i):(console.error("AssetImporter: Invalid asset or path",e),[]):[]}async importSingle(e,t,i,n){return(await this.import(e,t,i,n))?.[0]}async importPath(e,t={},i){const n=this._serializeOptions(t),s=this._cachedAssets.find(o=>o.path===e&&o._options===n);let a;return s?a=s:a={path:e},a._options=n,t.importedFile&&(a.file=t.importedFile),await this.importAsset(a,t,i,!1)}_serializeOptions(e){const{pathOverride:t,forceImport:i,reimportDisposed:n,fileHandler:s,importedFile:a,...o}=e;return JSON.stringify(o)}async importAsset(e,t={},i,n){if(!e)return[];if(!e.path&&!e.file&&!t.pathOverride)return[e];if(t.cacheAsset!==!1&&this.cacheImportedAssets&&!this._cachedAssets.includes(e)){if(Object.entries(e).length===1&&e.path){const l=this._cachedAssets.find(c=>c.path===e.path);l&&Object.assign(e,l)}const o=this._cachedAssets.findIndex(l=>l.path===e.path);o>=0&&this._cachedAssets.splice(o,1),this._cachedAssets.push(e)}let s=e?.preImported;!s&&e?.preImportedRaw&&(s=await e.preImportedRaw);const a=t.pathOverride||e.path;if(!t.forceImport&&s)return await this.processRaw(s,t,a);if(n===void 0&&(n=typeof e.file?.arrayBuffer=="function"),e.preImportedRaw=this._loadFile(a,typeof e.file?.arrayBuffer=="function"?e.file:void 0,t,i,n),s=await e.preImportedRaw,this.cacheImportedAssets||(e.preImportedRaw=void 0),s&&(s=await this.processRaw(s,t,a)),s){t.processRaw!==!1&&this.cacheImportedAssets&&(e.preImported=s);const o=[],l=c=>{c.userData?.rootSceneModelRoot?o.push(...c.children):o.push(c)};Array.isArray(s)?s.map(l):l(s),o.forEach(c=>c?.addEventListener&&c.addEventListener("dispose",()=>{e?.preImportedRaw&&(e.preImportedRaw=void 0),e?.preImported&&(e.preImported=void 0)}))}return s}async importFile(e,t={},i){return e?e instanceof File?this.importAsset(this._cachedAssets.find(n=>n.file===e)??{path:t.pathOverride||e.name||e.webkitRelativePath,file:e},t,i,!0):(console.error("AssetImporter: Invalid file",e),[]):[]}async importFiles(e,t={}){const i=new Map;let{allowedExtensions:n}=t;if(n&&n.length<1&&(n=void 0),e.size===0)return i;this.dispatchEvent({type:"importFiles",files:e,state:"start"});const s=[],a=[];if(e.forEach((o,l)=>{this.registerFile(l,o);const c=o.ext,h=o.mime;(c||h)&&(n?.includes((c||h||"").toLowerCase())??!0)&&(this._isRootFile(c)?s.push(l):a.push(l))}),s.length>0)for(const o of s){let l=await this._loadFile(o,void 0,t,void 0,!0);l&&(l=await this.processRaw(l,t,o)),i.set(o,l)}else for(const o of a){let l=await this._loadFile(o,void 0,t,void 0,!0);l&&(l=await this.processRaw(l,t,o)),i.set(o,l)}return this.dispatchEvent({type:"importFiles",files:e,state:"end"}),e.forEach((o,l)=>this.unregisterFile(l)),i}async _loadFile(e,t,i={},n,s=!1){this._cacheStoreInitPromise&&await this._cacheStoreInitPromise,this.dispatchEvent({type:"importFile",path:e,state:"downloading",progress:0});let a;try{const o=this.registerFile(e,t,i.fileExtension,i.fileHandler);if(!o)throw new Error("AssetImporter: Unable to find loader for "+e);this._rootContext={path:e,rootUrl:Rs.extractUrlBase(e)},o.importOptions=i,a=await o.loadAsync(e+(i.queryString?(e.includes("?")?"&":"?")+i.queryString:""),l=>{n&&n(l);const c=l.lengthComputable?l.total:void 0;this.dispatchEvent({type:"importFile",path:e,state:"downloading",loadedBytes:l.loaded||void 0,totalBytes:c&&c<l.loaded?l.loaded:l.total||void 0,progress:c&&c>0&&c>l.loaded?l.loaded/c:1})}),o.transform&&(a=await o.transform(a,i)),delete o.importOptions,this._rootContext=void 0,t?this._logger("AssetImporter: loaded",e):this._logger("AssetImporter: downloaded",e),t&&this.unregisterFile(e)}catch(o){return console.error("AssetImporter: Unable to import file",e,t),console.error(o),console.error(o?.stack),this.dispatchEvent({type:"importFile",path:e,state:"error",error:o}),t&&this.unregisterFile(e),[]}if(a&&typeof a=="object"&&!Array.isArray(a)){if(i.fileHandler&&!i.fileExtension&&console.warn("AssetImporter - Pass fileExtension to options when using fileHandler to be able to use `rootPath`",i.fileHandler,e),!s&&!e.startsWith("blob:")&&!e.startsWith("data:")&&(a.__rootPath=e,i)){const l=this._serializeOptions(i);l&&(a.__rootPathOptions=JSON.parse(l))}const o=t||this._fileDatabase.get(e);o&&(a.__rootBlob=o)}return a}registerFile(e,t,i,n){const s=e.startsWith("data:")||!1;s||(e=e.replace(/\?.*$/,""));const a=i||(s?void 0:t?.ext??Fu(t?.name??e.trim())?.toLowerCase()),o=(t?.mime??s)&&e.slice(0,e.indexOf(";")).split(":")[1]||void 0;return t&&(t.name===void 0&&(t.name=e),t.ext||(t.ext=a),t.mime||(t.mime=o),this._fileDatabase.has(e)&&(console.warn("AssetImporter: File already registered, replacing",e),this.unregisterFile(e)),this._fileDatabase.set(e,t)),n||this._getLoader(e,a,o)||this._createLoader(e,a,o)}unregisterFile(e){e=e.replace(/\?.*$/,"");const t=this._fileDatabase.get(e);t?.objectUrl&&(URL.revokeObjectURL(t.objectUrl),t.objectUrl=void 0),t&&this._fileDatabase.delete(e)}async processRaw(e,t,i){if(!e)return[];if(t.processImported!==void 0&&(console.error("AssetImporter: processImported is deprecated, use processRaw instead"),t.processRaw=t.processImported),Array.isArray(e)){const o=[];for(const l of e)o.push(...await this.processRaw(l,t,i));return o}if(t.processRaw===!1)return[e];if(e.assetImporterProcessed&&!t.forceImporterReprocess)return[e];const n=e.__rootPath,s=e.__rootPathOptions,a=e.__rootBlob;if(e.userData){const o=e.userData;!o.rootPath&&n&&!n.startsWith("blob:")&&(o.rootPath=n,s&&(o.rootPathOptions=s)),a&&(o.__sourceBlob=a,o.__needsSourceBuffer&&(o.__sourceBuffer=await a.arrayBuffer(),delete o.__needsSourceBuffer))}return!i&&e.userData?.rootPath&&(i=e.userData.rootPath),this.dispatchEvent({type:"processRawStart",data:e,options:t,path:i}),e.isTexture&&t._testDataTextureComplete&&(e.isDataTexture&&e.image?.data&&(e.image.complete=!0),e.image?.complete&&(e.needsUpdate=!0)),e?.userData&&e.userData.rootSceneModelRoot&&(e._childrenCopy=[...e.children]),this.autoSetName&&e.name===""&&(e.name=(a?.filePath||a?.name||n||"").replace(/^\/|\/$/,"").split("/").pop()),e.assetImporterProcessed=!0,this.dispatchEvent({type:"processRaw",data:e,options:t,path:i}),e instanceof Map&&t.autoImportZipContents!==!1?[...(await this.importFiles(e,t)).values()].flat():[e]}async processRawSingle(e,t,i){return(await this.processRaw(e,t,i))[0]}dispose(){this.clearCache()}clearCache(){this._cachedAssets=[],this.unregisterAllFiles(),this.clearLoaderCache()}unregisterAllFiles(){const e=[...this._fileDatabase.keys()];for(const t of e)this.unregisterFile(t)}clearLoaderCache(){for(const e of this._loaderCache)e.loader?.dispose&&e.loader?.dispose();this._loaderCache=[]}resolveURL(e){return this._loadingManager.resolveURL(e)}addURLModifier(e){this._urlModifiers.push(e)}removeURLModifier(e){const t=this._urlModifiers.indexOf(e);t>=0&&this._urlModifiers.splice(t,1)}_urlModifier(e){e=this._urlModifiers.reduce((a,o)=>o(a),e);let t=decodeURI(e);const i=this._rootContext?.rootUrl;!t.includes("://")&&i&&!t.startsWith(i)&&(t=i+t),t=t.replace("./",""),t=t.replace(/^(\/\/)/,"/"),t=t.replace(/\?.*$/,"");const n=this._fileDatabase.get(t);return n?n.ext?(n.objectUrl||(n.objectUrl=URL.createObjectURL(n)+"#"+t),n.objectUrl):(console.error("Unable to determine file extension",n),e):e}_isRootFile(e,t){return t=t?.toLowerCase(),e=e?.toLowerCase(),this.importers.find(i=>i.root&&(e&&it(i.ext)?.includes(e.toLowerCase())||t&&i.mime.includes(t.toLowerCase())))!=null}_getImporter(e,t,i,n=!1){return i=i?.toLowerCase(),t=t?.toLowerCase(),this.importers.find(s=>n&&!s.root?!1:!!(i&&s.mime?.find(a=>i===a)||it(s.ext)?.find(a=>t?a===t:e?.toLowerCase()?.endsWith("."+a)||a?.startsWith("data:")&&e?.startsWith(a))))}_getLoader(e,t,i){return!t&&!i&&e&&(t=Fu(e).toLowerCase()),i=i?.toLowerCase().trim(),t=t?.toLowerCase().trim(),(e?this._loadingManager.getHandler(e.trim()):void 0)||this._loaderCache.find(n=>t&&n.ext.includes(t)||i&&n.mime.includes(i))?.loader}_createLoader(e,t,i){const n=this._getImporter(e,t,i);if(!n)return;const s=n.ctor(this);if(s)return it(n.ext)?.forEach(a=>{const o=new RegExp(a.startsWith("data:")?"^"+Nu(a)+"[\\/\\+\\:\\,\\;]":"\\."+a+"$","i");this._loadingManager.addHandler(o,s)}),n.mime?.forEach(a=>{const o=new RegExp("^data:"+Nu(a)+"[\\/\\+\\:\\,\\;]","i");this._loadingManager.addHandler(o,s)}),this._loaderCache.push({loader:s,ext:it(n.ext)||[],mime:n.mime}),this.dispatchEvent({type:"loaderCreate",loader:s}),s}_initCacheStorage(e,t){if(t===!0&&window?.caches){this._cacheStoreInitPromise=window.caches.open?.("threepipe-assetmanager").then(i=>{this._initCacheStorage(e,i),this._storage=i,this._cacheStoreInitPromise=void 0});return}if(e||t){e&&(di.enabled=!0);const i=t&&window.Cache&&typeof window.Cache=="function"&&t instanceof window.Cache?t:void 0;zS(i)}this._storage=typeof t=="boolean"?void 0:t}addEventListener(e,t){if(super.addEventListener(e,t),e==="loaderCreate")for(const i of this._loaderCache)this.dispatchEvent({type:"loaderCreate",loader:i.loader})}_onLoad(){this.dispatchEvent({type:"onLoad"})}_onProgress(e,t,i){this.dispatchEvent({type:"onProgress",url:e,loaded:t,total:i})}_onError(e){this.dispatchEvent({type:"onError",url:e})}_onStart(e,t,i){this.dispatchEvent({type:"onStart",url:e,loaded:t,total:i})}async processImported(e,t,i){return console.error("processImported is deprecated. Use processRaw instead."),await this.processRaw(e,t,i)}};jr.DummyMaterial=new ys({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),jr.DummyLineBasicMaterial=new $n({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),jr.DummyLineMaterial=new ji({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),jr.DummyGeometry=new $e,jr.DummyMaterial.uiConfig={},jr.DummyLineBasicMaterial.uiConfig={},jr.DummyLineMaterial.uiConfig={},jr.DummyGeometry.uiConfig={};let Bs=jr,Cd,v0,sh,Xm;function _0(r,e=1/0,t=null){v0||(v0=new Er(2,2,1,1)),sh||(sh=new nn({uniforms:{blitTexture:new Up(r)},vertexShader:`
			varying vec2 vUv;
			void main(){
				vUv = uv;
				gl_Position = vec4(position.xy * 1.0,0.,.999999);
			}`,fragmentShader:`
			uniform sampler2D blitTexture; 
			varying vec2 vUv;

			void main(){ 
				gl_FragColor = vec4(vUv.xy, 0, 1);
				
				#ifdef IS_SRGB
				gl_FragColor = LinearTosRGB( texture2D( blitTexture, vUv) );
				#else
				gl_FragColor = texture2D( blitTexture, vUv);
				#endif
			}`})),sh.uniforms.blitTexture.value=r,sh.defines.IS_SRGB=r.colorSpace==vt,sh.needsUpdate=!0,Xm||(Xm=new ye(v0,sh),Xm.frustumCulled=!1);const i=new Vi,n=new qa;n.add(Xm),t===null&&(t=Cd=new Xf({antialias:!1}));const s=Math.min(r.image.width,e),a=Math.min(r.image.height,e);t.setSize(s,a),t.clear(),t.render(n,i);const o=document.createElement("canvas"),l=o.getContext("2d");o.width=s,o.height=a,l.drawImage(t.domElement,0,0,s,a);const c=new Wo(o);return c.minFilter=r.minFilter,c.magFilter=r.magFilter,c.wrapS=r.wrapS,c.wrapT=r.wrapT,c.name=r.name,Cd&&(Cd.forceContextLoss(),Cd.dispose(),Cd=null),c}const YM={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class xd{constructor(){this.pluginCallbacks=[],this.register(function(e){return new Gk(e)}),this.register(function(e){return new zk(e)}),this.register(function(e){return new Qk(e)}),this.register(function(e){return new jk(e)}),this.register(function(e){return new Wk(e)}),this.register(function(e){return new qk(e)}),this.register(function(e){return new Vk(e)}),this.register(function(e){return new Hk(e)}),this.register(function(e){return new Xk(e)}),this.register(function(e){return new Yk(e)}),this.register(function(e){return new $k(e)}),this.register(function(e){return new Kk(e)}),this.register(function(e){return new Jk(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,n,s){const a=s||new iT,o=[];for(let l=0,c=this.pluginCallbacks.length;l<c;l++)o.push(this.pluginCallbacks[l](a));a.setPlugins(o),a.write(e,t,n).catch(i)}parseAsync(e,t){const i=this;return new Promise(function(n,s){i.parse(e,n,s,t)})}}const kt={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},b0="KHR_mesh_quantization",Ls={};Ls[pi]=kt.NEAREST,Ls[Jh]=kt.NEAREST_MIPMAP_NEAREST,Ls[Na]=kt.NEAREST_MIPMAP_LINEAR,Ls[st]=kt.LINEAR,Ls[Po]=kt.LINEAR_MIPMAP_NEAREST,Ls[Ln]=kt.LINEAR_MIPMAP_LINEAR,Ls[ui]=kt.CLAMP_TO_EDGE,Ls[Bn]=kt.REPEAT,Ls[Zr]=kt.MIRRORED_REPEAT;const $M={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},Rk=new se,KM=12,Bk=1179937895,Lk=2,JM=8,Ok=1313821514,Uk=5130562;function Sd(r,e){return r.length===e.length&&r.every(function(t,i){return t===e[i]})}function Fk(r){return new TextEncoder().encode(r).buffer}function Nk(r){return Sd(r.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function kk(r,e,t){const i={min:new Array(r.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(r.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let n=e;n<e+t;n++)for(let s=0;s<r.itemSize;s++){let a;r.itemSize>4?a=r.array[n*r.itemSize+s]:(s===0?a=r.getX(n):s===1?a=r.getY(n):s===2?a=r.getZ(n):s===3&&(a=r.getW(n)),r.normalized===!0&&(a=Ut.normalize(a,r.array))),i.min[s]=Math.min(i.min[s],a),i.max[s]=Math.max(i.max[s],a)}return i}function ZM(r){return Math.ceil(r/4)*4}function Ym(r,e=0){const t=ZM(r.byteLength);if(t!==r.byteLength){const i=new Uint8Array(t);if(i.set(new Uint8Array(r)),e!==0)for(let n=r.byteLength;n<t;n++)i[n]=e;return i.buffer}return r}function eT(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function tT(r,e){if(r.toBlob!==void 0)return new Promise(i=>r.toBlob(i,e));let t;return e==="image/jpeg"?t=.92:e==="image/webp"&&(t=.8),r.convertToBlob({type:e,quality:t})}class iT{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map}}setPlugins(e){this.plugins=e}async write(e,t,i={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1,ignoreInvalidMorphTargetTracks:!1,ignoreEmptyTextures:!1},i),this.options.animations.length>0&&(this.options.trs=!0),this.processInput(e),await Promise.all(this.pending);const n=this,s=n.buffers,a=n.json;i=n.options;const o=n.extensionsUsed,l=n.extensionsRequired,c=new Blob(s,{type:"application/octet-stream"}),h=Object.keys(o),u=Object.keys(l);if(h.length>0&&(a.extensionsUsed=h),u.length>0&&(a.extensionsRequired=u),a.buffers&&a.buffers.length>0&&(a.buffers[0].byteLength=c.size),i.binary===!0){const d=new FileReader;d.readAsArrayBuffer(c),d.onloadend=function(){const p=Ym(d.result),m=new DataView(new ArrayBuffer(JM));m.setUint32(0,p.byteLength,!0),m.setUint32(4,Uk,!0);const A=Ym(Fk(JSON.stringify(a)),32),g=new DataView(new ArrayBuffer(JM));g.setUint32(0,A.byteLength,!0),g.setUint32(4,Ok,!0);const y=new ArrayBuffer(KM),_=new DataView(y);_.setUint32(0,Bk,!0),_.setUint32(4,Lk,!0);const v=KM+g.byteLength+A.byteLength+m.byteLength+p.byteLength;_.setUint32(8,v,!0);const b=new Blob([y,g,A,m,p],{type:"application/octet-stream"}),T=new FileReader;T.readAsArrayBuffer(b),T.onloadend=function(){t(T.result)}}}else if(a.buffers&&a.buffers.length>0){const d=new FileReader;d.readAsDataURL(c),d.onloadend=function(){const p=d.result;a.buffers[0].uri=p,t(a)}}else t(a)}serializeUserData(e,t){if(Object.keys(e.userData).length===0)return;const i=this.options,n=this.extensionsUsed;try{const s=JSON.parse(JSON.stringify(e.userData));if(i.includeCustomExtensions&&s.gltfExtensions){t.extensions===void 0&&(t.extensions={});for(const a in s.gltfExtensions)t.extensions[a]=s.gltfExtensions[a],n[a]=!0;delete s.gltfExtensions}Object.keys(s).length>0&&(t.extras=s)}catch(s){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+s.message),console.warn({...e.userData})}}getUID(e,t=!1){if(this.uids.has(e)===!1){const n=new Map;n.set(!0,this.uid++),n.set(!1,this.uid++),this.uids.set(e,n)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const i=new x;for(let n=0,s=e.count;n<s;n++)if(Math.abs(i.fromBufferAttribute(e,n).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);const i=e.clone(),n=new x;for(let s=0,a=i.count;s<a;s++)n.fromBufferAttribute(i,s),n.x===0&&n.y===0&&n.z===0?n.setX(1):n.normalize(),i.setXYZ(s,n.x,n.y,n.z);return t.attributesNormalized.set(e,i),i}applyTextureTransform(e,t){let i=!1;const n={};(t.offset.x!==0||t.offset.y!==0)&&(n.offset=t.offset.toArray(),i=!0),t.rotation!==0&&(n.rotation=t.rotation,i=!0),(t.repeat.x!==1||t.repeat.y!==1)&&(n.scale=t.repeat.toArray(),i=!0),i&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=n,this.extensionsUsed.KHR_texture_transform=!0)}buildMetalRoughTexture(e,t){if(e===t)return e;function i(p){return p.colorSpace===vt?function(A){return A<.04045?A*.0773993808:Math.pow(A*.9478672986+.0521327014,2.4)}:function(A){return A}}console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),e instanceof ua&&(e=_0(e)),t instanceof ua&&(t=_0(t));const n=e?e.image:null,s=t?t.image:null,a=Math.max(n?n.width:0,s?s.width:0),o=Math.max(n?n.height:0,s?s.height:0),l=eT();l.width=a,l.height=o;const c=l.getContext("2d");c.fillStyle="#00ffff",c.fillRect(0,0,a,o);const h=c.getImageData(0,0,a,o);if(n){c.drawImage(n,0,0,a,o);const p=i(e),m=c.getImageData(0,0,a,o).data;for(let A=2;A<m.length;A+=4)h.data[A]=p(m[A]/256)*256}if(s){c.drawImage(s,0,0,a,o);const p=i(t),m=c.getImageData(0,0,a,o).data;for(let A=1;A<m.length;A+=4)h.data[A]=p(m[A]/256)*256}c.putImageData(h,0,0);const d=(e||t).clone();return d.source=new na(l),d.colorSpace=si,d.channel=(e||t).channel,e&&t&&e.channel!==t.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),d}processBuffer(e){const t=this.json,i=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),i.push(e),0}processBufferView(e,t,i,n,s){const a=this.json;a.bufferViews||(a.bufferViews=[]);let o;switch(t){case kt.BYTE:case kt.UNSIGNED_BYTE:o=1;break;case kt.SHORT:case kt.UNSIGNED_SHORT:o=2;break;default:o=4}let l=e.itemSize*o;s===kt.ARRAY_BUFFER&&(l=Math.ceil(l/4)*4);const c=ZM(n*l),h=new DataView(new ArrayBuffer(c));let u=0;for(let m=i;m<i+n;m++){for(let A=0;A<e.itemSize;A++){let g;e.itemSize>4?g=e.array[m*e.itemSize+A]:(A===0?g=e.getX(m):A===1?g=e.getY(m):A===2?g=e.getZ(m):A===3&&(g=e.getW(m)),e.normalized===!0&&(g=Ut.normalize(g,e.array))),t===kt.FLOAT?h.setFloat32(u,g,!0):t===kt.INT?h.setInt32(u,g,!0):t===kt.UNSIGNED_INT?h.setUint32(u,g,!0):t===kt.SHORT?h.setInt16(u,g,!0):t===kt.UNSIGNED_SHORT?h.setUint16(u,g,!0):t===kt.BYTE?h.setInt8(u,g):t===kt.UNSIGNED_BYTE&&h.setUint8(u,g),u+=o}u%l!==0&&(u+=l-u%l)}const d={buffer:this.processBuffer(h.buffer),byteOffset:this.byteOffset,byteLength:c};return s!==void 0&&(d.target=s),s===kt.ARRAY_BUFFER&&(d.byteStride=l),this.byteOffset+=c,a.bufferViews.push(d),{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,i=t.json;return i.bufferViews||(i.bufferViews=[]),new Promise(function(n){const s=new FileReader;s.readAsArrayBuffer(e),s.onloadend=function(){const a=Ym(s.result),o={buffer:t.processBuffer(a),byteOffset:t.byteOffset,byteLength:a.byteLength};t.byteOffset+=a.byteLength,n(i.bufferViews.push(o)-1)}})}processBufferViewImageBuffer(e){const t=this,i=t.json;i.bufferViews||(i.bufferViews=[]),e=Ym(e);const n={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};return t.byteOffset+=e.byteLength,i.bufferViews.push(n)-1}processAccessor(e,t,i,n){const s=this.json,a={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let o;if(e.array.constructor===Float32Array)o=kt.FLOAT;else if(e.array.constructor===Int32Array)o=kt.INT;else if(e.array.constructor===Uint32Array)o=kt.UNSIGNED_INT;else if(e.array.constructor===Int16Array)o=kt.SHORT;else if(e.array.constructor===Uint16Array)o=kt.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)o=kt.BYTE;else if(e.array.constructor===Uint8Array)o=kt.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(i===void 0&&(i=0),(n===void 0||n===1/0)&&(n=e.count),n===0)return null;const l=kk(e,i,n);let c;t!==void 0&&(c=e===t.index?kt.ELEMENT_ARRAY_BUFFER:kt.ARRAY_BUFFER);const h=this.processBufferView(e,o,i,n,c),u={bufferView:h.id,byteOffset:h.byteOffset,componentType:o,count:n,max:l.max,min:l.min,type:a[e.itemSize]};return e.normalized===!0&&(u.normalized=!0),s.accessors||(s.accessors=[]),s.accessors.push(u)-1}processImage(e,t,i,n="image/png",s=void 0,a=void 0){if(e!==null){const o=this,l=o.cache,c=o.json,h=o.options,u=o.pending;l.images.has(e)||l.images.set(e,{});const d=l.images.get(e),p=n+":flipY/"+i.toString()+(s||a?";"+s+";"+a:"");if(d[p]!==void 0)return d[p];c.images||(c.images=[]);const m={mimeType:n},A=eT();A.width=Math.min(s||e.width,h.maxTextureSize),A.height=Math.min(a||e.height,h.maxTextureSize);const g=A.getContext("2d");if(i===!0&&(g.translate(0,A.height),g.scale(1,-1)),e.data!==void 0){t!==Kt&&console.error("GLTFExporter: Only RGBAFormat is supported.",t),(e.width>h.maxTextureSize||e.height>h.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const _=new Uint8ClampedArray(e.height*e.width*4);for(let v=0;v<_.length;v+=4)_[v+0]=e.data[v+0],_[v+1]=e.data[v+1],_[v+2]=e.data[v+2],_[v+3]=e.data[v+3];g.putImageData(new ImageData(_,e.width,e.height),0,0)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)g.drawImage(e,0,0,A.width,A.height);else throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");h.binary===!0?u.push(tT(A,n).then(_=>o.processBufferViewImage(_)).then(_=>{m.bufferView=_})):A.toDataURL!==void 0?m.uri=A.toDataURL(n):u.push(tT(A,n).then(_=>new FileReader().readAsDataURL(_)).then(_=>{m.uri=_}));const y=c.images.push(m)-1;return d[p]=y,y}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const t=this.json;t.samplers||(t.samplers=[]);const i={magFilter:Ls[e.magFilter],minFilter:Ls[e.minFilter],wrapS:Ls[e.wrapS],wrapT:Ls[e.wrapT]};return t.samplers.push(i)-1}processTexture(e){const i=this.options,n=this.cache,s=this.json;if(n.textures.has(e))return n.textures.get(e);s.textures||(s.textures=[]),e instanceof ua&&!e.source._canSerialize&&(e=_0(e,i.maxTextureSize));let a=e.userData.mimeType;a==="image/webp"&&(a="image/png"),a==="image/jpg"&&(a="image/jpeg");const o=["image/jpeg","image/png"],l={sampler:this.processSampler(e),source:!a||o.includes(a)?this.processImage(e.image,e.format,e.flipY,a):null};e.name&&(l.name=e.name),this._invokeAll(function(h){h.writeTexture&&h.writeTexture(e,l)}),l.source===null&&console.error("GLTFExporter: Unsupported mime type: "+a+". Cannot export texture.",e);const c=s.textures.push(l)-1;return n.textures.set(e,c),c}processMaterial(e){const t=this.cache,i=this.json;if(t.materials.has(e))return t.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;i.materials||(i.materials=[]);const n={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const s=e.color.toArray().concat([e.opacity]);if(Sd(s,[1,1,1,1])||(n.pbrMetallicRoughness.baseColorFactor=s),e.isMeshStandardMaterial?(n.pbrMetallicRoughness.metallicFactor=e.metalness,n.pbrMetallicRoughness.roughnessFactor=e.roughness):(n.pbrMetallicRoughness.metallicFactor=.5,n.pbrMetallicRoughness.roughnessFactor=.5),this.checkEmptyMap(e.metalnessMap)||this.checkEmptyMap(e.roughnessMap)){const o=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),l={index:this.processTexture(o),channel:o.channel};this.applyTextureTransform(l,o),n.pbrMetallicRoughness.metallicRoughnessTexture=l}if(this.checkEmptyMap(e.map)){const o={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(o,e.map),n.pbrMetallicRoughness.baseColorTexture=o}if(e.emissive){const o=e.emissive;if(Math.max(o.r,o.g,o.b)>0&&(n.emissiveFactor=e.emissive.toArray()),this.checkEmptyMap(e.emissiveMap)){const c={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(c,e.emissiveMap),n.emissiveTexture=c}}if(this.checkEmptyMap(e.normalMap)){const o={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(o.scale=e.normalScale.x),this.applyTextureTransform(o,e.normalMap),n.normalTexture=o}if(this.checkEmptyMap(e.aoMap)){const o={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(o.strength=e.aoMapIntensity),this.applyTextureTransform(o,e.aoMap),n.occlusionTexture=o}e.transparent?n.alphaMode="BLEND":e.alphaTest>0&&(n.alphaMode="MASK",n.alphaCutoff=e.alphaTest),e.side===Zi&&(n.doubleSided=!0),e.name!==""&&(n.name=e.name),this.serializeUserData(e,n),this._invokeAll(function(o){o.writeMaterial&&o.writeMaterial(e,n)});const a=i.materials.push(n)-1;return t.materials.set(e,a),a}processMesh(e){const t=this.cache,i=this.json,n=[e.geometry.uuid];if(Array.isArray(e.material))for(let b=0,T=e.material.length;b<T;b++)n.push(e.material[b].uuid);else n.push(e.material.uuid);const s=n.join(":");if(t.meshes.has(s))return t.meshes.get(s);const a=e.geometry;let o;e.isLineSegments?o=kt.LINES:e.isLineLoop?o=kt.LINE_LOOP:e.isLine?o=kt.LINE_STRIP:e.isPoints?o=kt.POINTS:o=e.material.wireframe?kt.LINES:kt.TRIANGLES;const l={},c={},h=[],u=[],d={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},p=a.getAttribute("normal");p!==void 0&&!this.isNormalizedNormalAttribute(p)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),a.setAttribute("normal",this.createNormalizedNormalAttribute(p)));let m=null;for(let b in a.attributes){if(b.slice(0,5)==="morph")continue;const T=a.attributes[b];if(b=d[b]||b.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(b)||(b="_"+b),t.attributes.has(this.getUID(T))){c[b]=t.attributes.get(this.getUID(T));continue}m=null;const M=T.array;b==="JOINTS_0"&&!(M instanceof Uint16Array)&&!(M instanceof Uint8Array)&&(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),m=new Xe(new Uint16Array(M),T.itemSize,T.normalized));const S=this.processAccessor(m||T,a);S!==null&&(b.startsWith("_")||this.detectMeshQuantization(b,T),c[b]=S,t.attributes.set(this.getUID(T),S))}if(p!==void 0&&a.setAttribute("normal",p),Object.keys(c).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const b=[],T=[],E={};if(e.morphTargetDictionary!==void 0)for(const M in e.morphTargetDictionary)E[e.morphTargetDictionary[M]]=M;for(let M=0;M<e.morphTargetInfluences.length;++M){const S={};let w=!1;for(const C in a.morphAttributes){if(C!=="position"&&C!=="normal"){w||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),w=!0);continue}const D=a.morphAttributes[C][M],O=C.toUpperCase(),F=a.attributes[C];if(t.attributes.has(this.getUID(D,!0))){S[O]=t.attributes.get(this.getUID(D,!0));continue}const G=D.clone();if(!a.morphTargetsRelative)for(let j=0,W=D.count;j<W;j++)for(let K=0;K<D.itemSize;K++)K===0&&G.setX(j,D.getX(j)-F.getX(j)),K===1&&G.setY(j,D.getY(j)-F.getY(j)),K===2&&G.setZ(j,D.getZ(j)-F.getZ(j)),K===3&&G.setW(j,D.getW(j)-F.getW(j));S[O]=this.processAccessor(G,a),t.attributes.set(this.getUID(F,!0),S[O])}u.push(S),b.push(e.morphTargetInfluences[M]),e.morphTargetDictionary!==void 0&&T.push(E[M])}l.weights=b,T.length>0&&(l.extras={},l.extras.targetNames=T)}const A=Array.isArray(e.material);if(A&&a.groups.length===0)return null;let g=!1;if(A&&a.index===null){const b=[];for(let T=0,E=a.attributes.position.count;T<E;T++)b[T]=T;a.setIndex(b),g=!0}const y=A?e.material:[e.material],_=A?a.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let b=0,T=_.length;b<T;b++){const E={mode:o,attributes:c};if(this.serializeUserData(a,E),u.length>0&&(E.targets=u),a.index!==null){let S=this.getUID(a.index);(_[b].start!==void 0||_[b].count!==void 0)&&(S+=":"+_[b].start+":"+_[b].count),t.attributes.has(S)?E.indices=t.attributes.get(S):(E.indices=this.processAccessor(a.index,a,_[b].start,_[b].count),t.attributes.set(S,E.indices)),E.indices===null&&delete E.indices}const M=this.processMaterial(y[_[b].materialIndex]);M!==null&&(E.material=M),h.push(E)}g===!0&&a.setIndex(null),l.primitives=h,i.meshes||(i.meshes=[]),this._invokeAll(function(b){b.writeMesh&&b.writeMesh(e,l)});const v=i.meshes.push(l)-1;return t.meshes.set(s,v),v}detectMeshQuantization(e,t){if(this.extensionsUsed[b0])return;let i;switch(t.array.constructor){case Int8Array:i="byte";break;case Uint8Array:i="unsigned byte";break;case Int16Array:i="short";break;case Uint16Array:i="unsigned short";break;default:return}t.normalized&&(i+=" normalized");const n=e.split("_",1)[0];YM[n]&&YM[n].includes(i)&&(this.extensionsUsed[b0]=!0,this.extensionsRequired[b0]=!0)}processCamera(e){const t=this.json;t.cameras||(t.cameras=[]);const i=e.isOrthographicCamera,n={type:i?"orthographic":"perspective"};return i?n.orthographic={xmag:e.right*2,ymag:e.top*2,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:n.perspective={aspectRatio:e.aspect,yfov:Ut.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(n.name=e.type),t.cameras.push(n)-1}processAnimation(e,t){const i=this.json,n=this.nodeMap;i.animations||(i.animations=[]);try{e=xd.Utils.mergeMorphTargetTracks(e.clone(),t)}catch(c){if(console.warn('THREE.GLTFExporter: Could not export animation clip "%s".',e.name),!this.options.ignoreInvalidMorphTargetTracks)throw c;return console.error(c),null}const s=e.tracks,a=[],o=[];for(let c=0;c<s.length;++c){const h=s[c],u=Ct.parseTrackName(h.name);let d=Ct.findNode(t,u.nodeName);const p=$M[u.propertyName];if(u.objectName==="bones"&&(d.isSkinnedMesh===!0?d=d.skeleton.getBoneByName(u.objectIndex):d=void 0),!d||!p)return console.warn('THREE.GLTFExporter: Could not export animation track "%s".',h.name),null;const m=1;let A=h.values.length/h.times.length;p===$M.morphTargetInfluences&&(A/=d.morphTargetInfluences.length);let g;h.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline===!0?(g="CUBICSPLINE",A/=3):h.getInterpolation()===Jl?g="STEP":g="LINEAR",o.push({input:this.processAccessor(new Xe(h.times,m)),output:this.processAccessor(new Xe(h.values,A)),interpolation:g}),a.push({sampler:o.length-1,target:{node:n.get(d),path:p}})}const l={name:e.name||"clip_"+i.animations.length,samplers:o,channels:a};return this.serializeUserData(e,l),i.animations.push(l),i.animations.length-1}processSkin(e){const t=this.json,i=this.nodeMap,n=t.nodes[i.get(e)],s=e.skeleton;if(s===void 0)return null;const a=e.skeleton.bones[0];if(a===void 0)return null;const o=[],l=new Float32Array(s.bones.length*16),c=new pe;for(let u=0;u<s.bones.length;++u)o.push(i.get(s.bones[u])),c.copy(s.boneInverses[u]),c.multiply(e.bindMatrix).toArray(l,u*16);return t.skins===void 0&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new Xe(l,16)),joints:o,skeleton:i.get(a)}),n.skin=t.skins.length-1}processNode(e){const t=this.json,i=this.options,n=this.nodeMap;t.nodes||(t.nodes=[]);const s={};if(i.trs){const o=e.quaternion.toArray(),l=e.position.toArray(),c=e.scale.toArray();Sd(o,[0,0,0,1])||(s.rotation=o),Sd(l,[0,0,0])||(s.translation=l),Sd(c,[1,1,1])||(s.scale=c)}else e.matrixAutoUpdate&&e.updateMatrix(),Nk(e.matrix)===!1&&(s.matrix=e.matrix.elements);if(e.name!==""&&(s.name=String(e.name)),this.serializeUserData(e,s),e.isMesh||e.isLine||e.isPoints){const o=this.processMesh(e);o!==null&&(s.mesh=o)}else e.isCamera&&(s.camera=this.processCamera(e));if(e.isSkinnedMesh&&this.skins.push(e),e.children.length>0){const o=[];for(let l=0,c=e.children.length;l<c;l++){const h=e.children[l];if(h.visible||i.onlyVisible===!1){const u=this.processNode(h);u!==null&&o.push(u)}}o.length>0&&(s.children=o)}this._invokeAll(function(o){o.writeNode&&o.writeNode(e,s)});const a=t.nodes.push(s)-1;return n.set(e,a),a}processScene(e){const t=this.json,i=this.options;t.scenes||(t.scenes=[],t.scene=0);const n={};e.name!==""&&(n.name=e.name),t.scenes.push(n);const s=[];for(let a=0,o=e.children.length;a<o;a++){const l=e.children[a];if(l.visible||i.onlyVisible===!1){const c=this.processNode(l);c!==null&&s.push(c)}}s.length>0&&(n.nodes=s),this.serializeUserData(e,n)}processObjects(e){const t=new qa;t.name="AuxScene";for(let i=0;i<e.length;i++)t.children.push(e[i]);this.processScene(t)}processInput(e){const t=this.options;e=e instanceof Array?e:[e],this._invokeAll(function(n){n.beforeParse&&n.beforeParse(e)});const i=[];for(let n=0;n<e.length;n++)e[n]instanceof qa?this.processScene(e[n]):i.push(e[n]);i.length>0&&this.processObjects(i);for(let n=0;n<this.skins.length;++n)this.processSkin(this.skins[n]);for(let n=0;n<t.animations.length;++n)this.processAnimation(t.animations[n],e[0]);this._invokeAll(function(n){n.afterParse&&n.afterParse(e)})}_invokeAll(e){for(let t=0,i=this.plugins.length;t<i;t++)e(this.plugins[t])}checkEmptyMap(e){return!!e&&(!this.options.ignoreEmptyTextures||!!e.image)}}class Gk{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight){console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.",e);return}const i=this.writer,n=i.json,s=i.extensionsUsed,a={};e.name&&(a.name=e.name),a.color=e.color.toArray(),a.intensity=e.intensity,e.isDirectionalLight?a.type="directional":e.isPointLight?(a.type="point",e.distance>0&&(a.range=e.distance)):e.isSpotLight&&(a.type="spot",e.distance>0&&(a.range=e.distance),a.spot={},a.spot.innerConeAngle=(1-e.penumbra)*e.angle,a.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),s[this.name]||(n.extensions=n.extensions||{},n.extensions[this.name]={lights:[]},s[this.name]=!0);const o=n.extensions[this.name].lights;o.push(a),t.extensions=t.extensions||{},t.extensions[this.name]={light:o.length-1}}}let zk=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}writeMaterial(e,t){if(!e.isMeshBasicMaterial)return;const n=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},n[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},Vk=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.clearcoat===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.clearcoatFactor=e.clearcoat,i.checkEmptyMap(e.clearcoatMap)){const a={index:i.processTexture(e.clearcoatMap),texCoord:e.clearcoatMap.channel};i.applyTextureTransform(a,e.clearcoatMap),s.clearcoatTexture=a}if(s.clearcoatRoughnessFactor=e.clearcoatRoughness,i.checkEmptyMap(e.clearcoatRoughnessMap)){const a={index:i.processTexture(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};i.applyTextureTransform(a,e.clearcoatRoughnessMap),s.clearcoatRoughnessTexture=a}if(i.checkEmptyMap(e.clearcoatNormalMap)){const a={index:i.processTexture(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};i.applyTextureTransform(a,e.clearcoatNormalMap),s.clearcoatNormalTexture=a}t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},Hk=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.iridescence===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.iridescenceFactor=e.iridescence,i.checkEmptyMap(e.iridescenceMap)){const a={index:i.processTexture(e.iridescenceMap),texCoord:e.iridescenceMap.channel};i.applyTextureTransform(a,e.iridescenceMap),s.iridescenceTexture=a}if(s.iridescenceIor=e.iridescenceIOR,s.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],s.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],i.checkEmptyMap(e.iridescenceThicknessMap)){const a={index:i.processTexture(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};i.applyTextureTransform(a,e.iridescenceThicknessMap),s.iridescenceThicknessTexture=a}t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},Qk=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.transmissionFactor=e.transmission,i.checkEmptyMap(e.transmissionMap)){const a={index:i.processTexture(e.transmissionMap),texCoord:e.transmissionMap.channel};i.applyTextureTransform(a,e.transmissionMap),s.transmissionTexture=a}t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},jk=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.thicknessFactor=e.thickness,i.checkEmptyMap(e.thicknessMap)){const a={index:i.processTexture(e.thicknessMap),texCoord:e.thicknessMap.channel};i.applyTextureTransform(a,e.thicknessMap),s.thicknessTexture=a}s.attenuationDistance=e.attenuationDistance,s.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},Wk=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.ior===1.5)return;const n=this.writer.extensionsUsed,s={};s.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},qk=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.specularIntensity===1&&e.specularColor.equals(Rk)&&!e.specularIntensityMap&&!e.specularColorMap)return;const i=this.writer,n=i.extensionsUsed,s={};if(i.checkEmptyMap(e.specularIntensityMap)){const a={index:i.processTexture(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};i.applyTextureTransform(a,e.specularIntensityMap),s.specularTexture=a}if(i.checkEmptyMap(e.specularColorMap)){const a={index:i.processTexture(e.specularColorMap),texCoord:e.specularColorMap.channel};i.applyTextureTransform(a,e.specularColorMap),s.specularColorTexture=a}s.specularFactor=e.specularIntensity,s.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},Xk=class{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.sheen<.001)return;const i=this.writer,n=i.extensionsUsed,s={};if(i.checkEmptyMap(e.sheenRoughnessMap)){const a={index:i.processTexture(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};i.applyTextureTransform(a,e.sheenRoughnessMap),s.sheenRoughnessTexture=a}if(i.checkEmptyMap(e.sheenColorMap)){const a={index:i.processTexture(e.sheenColorMap),texCoord:e.sheenColorMap.channel};i.applyTextureTransform(a,e.sheenColorMap),s.sheenColorTexture=a}s.sheenRoughnessFactor=e.sheenRoughness,s.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,t.extras=t.extras||{},t.extras.sheenFactor=e.sheen,n[this.name]=!0}},Yk=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.anisotropy==0)return;const i=this.writer,n=i.extensionsUsed,s={};if(i.checkEmptyMap(e.anisotropyMap)){const a={index:i.processTexture(e.anisotropyMap)};i.applyTextureTransform(a,e.anisotropyMap),s.anisotropyTexture=a}s.anisotropyStrength=e.anisotropy,s.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},$k=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.emissiveIntensity===1)return;const n=this.writer.extensionsUsed,s={};s.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},Kk=class{constructor(e){this.writer=e,this.name="EXT_materials_bump"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.bumpScale===1&&!e.bumpMap)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.bumpMap){const a={index:i.processTexture(e.bumpMap),texCoord:e.bumpMap.channel};i.applyTextureTransform(a,e.bumpMap),s.bumpTexture=a}s.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},Jk=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;const i=this.writer,n=e,s=new Float32Array(n.count*3),a=new Float32Array(n.count*4),o=new Float32Array(n.count*3),l=new pe,c=new x,h=new Qe,u=new x;for(let p=0;p<n.count;p++)n.getMatrixAt(p,l),l.decompose(c,h,u),c.toArray(s,p*3),h.toArray(a,p*4),u.toArray(o,p*3);const d={TRANSLATION:i.processAccessor(new Xe(s,3)),ROTATION:i.processAccessor(new Xe(a,4)),SCALE:i.processAccessor(new Xe(o,3))};n.instanceColor&&(d._COLOR_0=i.processAccessor(n.instanceColor)),t.extensions=t.extensions||{},t.extensions[this.name]={attributes:d},i.extensionsUsed[this.name]=!0,i.extensionsRequired[this.name]=!0}};xd.Utils={GLTFWriter:iT,insertKeyframe:function(r,e){const i=r.getValueSize(),n=new r.TimeBufferType(r.times.length+1),s=new r.ValueBufferType(r.values.length+i),a=r.createInterpolant(new r.ValueBufferType(i));let o;if(r.times.length===0){n[0]=e;for(let l=0;l<i;l++)s[l]=0;o=0}else if(e<r.times[0]){if(Math.abs(r.times[0]-e)<.001)return 0;n[0]=e,n.set(r.times,1),s.set(a.evaluate(e),0),s.set(r.values,i),o=0}else if(e>r.times[r.times.length-1]){if(Math.abs(r.times[r.times.length-1]-e)<.001)return r.times.length-1;n[n.length-1]=e,n.set(r.times,0),s.set(r.values,0),s.set(a.evaluate(e),r.values.length),o=n.length-1}else for(let l=0;l<r.times.length;l++){if(Math.abs(r.times[l]-e)<.001)return l;if(r.times[l]<e&&r.times[l+1]>e){n.set(r.times.slice(0,l+1),0),n[l+1]=e,n.set(r.times.slice(l+1),l+2),s.set(r.values.slice(0,(l+1)*i),0),s.set(a.evaluate(e),(l+1)*i),s.set(r.values.slice((l+1)*i),(l+2)*i),o=l+1;break}}return r.times=n,r.values=s,o},mergeMorphTargetTracks:function(r,e){const t=[],i={},n=r.tracks;for(let s=0;s<n.length;++s){let a=n[s];const o=Ct.parseTrackName(a.name),l=Ct.findNode(e,o.nodeName);if(o.propertyName!=="morphTargetInfluences"||o.propertyIndex===void 0){t.push(a);continue}if(a.createInterpolant!==a.InterpolantFactoryMethodDiscrete&&a.createInterpolant!==a.InterpolantFactoryMethodLinear){if(a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."),a=a.clone(),a.setInterpolation(Ro)}const c=l.morphTargetInfluences.length,h=l.morphTargetDictionary[o.propertyIndex];if(h===void 0)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let u;if(i[l.uuid]===void 0){u=a.clone();const p=new u.ValueBufferType(c*u.times.length);for(let m=0;m<u.times.length;m++)p[m*c+h]=u.values[m];u.name=(o.nodeName||"")+".morphTargetInfluences",u.values=p,i[l.uuid]=u,t.push(u);continue}const d=a.createInterpolant(new a.ValueBufferType(1));u=i[l.uuid];for(let p=0;p<u.times.length;p++)u.values[p*c+h]=d.evaluate(u.times[p]);for(let p=0;p<a.times.length;p++){const m=this.insertKeyframe(u,a.times[p]);u.values[m*c+h]=a.values[p]}}return r.tracks=t,r}};class nT extends xd.Utils.GLTFWriter{constructor(){super(),this.TPAssetVersion=1,this.serializationMeta=Fr(),this._defaultMaterial=new Ka,this.json.asset.subversion=this.TPAssetVersion}serializeUserData(e,t){const i=e.userData,n={};i.__disposed&&console.error("Serializing a disposed object",e),Object.entries(i).forEach(([a,o])=>{(!o||typeof o=="function"||o.isObject3D||o.isTexture||o.isMaterial||o.assetType!=null||a.startsWith("_"))&&(n[a]=o,delete i[a])});const s=ke.Serialize(i,this.serializationMeta);Object.entries(n).forEach(([a,o])=>{i[a]=o,delete n[a]}),e.userData=s,super.serializeUserData(e,t),e.userData=i}processObjects(e){e.length===1&&e[0]?.userData.rootSceneModelRoot?this.processScene(e[0]):super.processObjects(e)}processMaterial(e){if(this.cache.materials.has(e))return this.cache.materials.get(e);let t=e;(!t||t.isShaderMaterial)&&(t=this._defaultMaterial);const i=super.processMaterial(t);if(i===null)return console.error("GLTFWriter2: Unexpected error: Failed to process material",e),null;if(!e||t===e)return i;const n=JSON.stringify(this.json.materials[i]),s=JSON.parse(n),a=e.color?.isColor?e.color.toArray().concat([e.opacity]):null;a&&!a.every(l=>l===1)&&s.pbrMetallicRoughness&&(s.pbrMetallicRoughness.baseColorFactor=a),this.serializeUserData(e,s),this._invokeAll(l=>{l.writeMaterial&&l.writeMaterial(e,s)});const o=this.json.materials.push(s)-1;return this.cache.materials.set(e,o),o}processImageBlob(e,t){if(!e)return-1;const i=this.cache,n=this.options,s=this.pending,a=this.json,o=t.image;i.images.has(o)||i.images.set(o,{});const l=i.images.get(o),c=e.type+":flipY/"+t.flipY.toString();if(l[c]!==void 0)return l[c];a.images||(a.images=[]);const h={mimeType:e.type};n.binary===!0?s.push(new Promise(d=>{this.processBufferViewImage(e).then(p=>{h.bufferView=p,d()})})):s.push(qp(e).then(d=>{h.uri=d}));const u=a.images.push(h)-1;return l[c]=u,u}processSampler(e){return super.processSampler(e)}processTexture(e){const t=this.cache,i=this.json;if(t.textures.has(e))return t.textures.get(e);const n=e.source.data,s=e.userData.mimeType,a=!e.isRenderTargetTexture&&e.userData.rootPath&&typeof e.userData.rootPath=="string"&&Hc(e.userData.rootPath);a&&!this.options.exporterOptions.embedUrlImages&&(e.source.data&&(!this.options.exporterOptions.embedUrlImagePreviews||e.isDataTexture?e.source.data=null:e.source.data._savePreview=!0),delete e.userData.mimeType);const o=super.processTexture(e),l=i.textures[o];if(!l)return console.error("No texture def",o,e),o;if(a&&!this.options.exporterOptions.embedUrlImages){if(e.source.data?delete e.source.data._savePreview:e.source.data=n,e.userData.mimeType=s,!l)return console.error("textureDef is null",o,e),o;let c=e.userData.rootPath;const h=this.options.exporterOptions._basePath;if(h&&typeof c=="string"&&c.startsWith(h)&&(c=c.slice(h.length)),l.source>=0){const u=this.json.images[l.source];u.uri?console.warn("uri already set",u.uri):(u.uri=c,u.mimeType=s,u.extras||(u.extras={}),u.extras.flipY=e.flipY,u.extras.uri=c)}else l.source=this.processImageUri(e.image,c,e.flipY,s)}if(l.source<0)console.error("textureDef.source cannot be saved",l,e),delete l.source;else{const c=i.images?i.images[l.source]:null;c&&(c.extras||(c.extras={}),e.source&&(c.extras.uuid=e.source.uuid),c.extras.t_uuid=e.uuid)}return o}processImage(e,t,i,n="image/png"){return e?super.processImage(e,t,i,n,e._savePreview?32:void 0,e._savePreview?32:void 0):-1}processImageUri(e,t,i,n="image/png"){const s=this.cache,a=this.json;s.images.has(e)||s.images.set(e,{});const o=s.images.get(e),l=n+":flipY/"+i.toString();if(o[l]!==void 0)return o[l];a.images||(a.images=[]);const c={mimeType:n,uri:t,extras:{flipY:i}},h=a.images.push(c)-1;return o[l]=h,h}}const br=class br{};br.WebGiLightExtrasExtension="WEBGI_light_extras",br.Import=e=>({name:"__"+br.WebGiLightExtrasExtension,afterRoot:async t=>{(t.scenes||(t.scene?[t.scene]:[])).forEach(n=>{n.traverse(s=>{if(!s.isLight)return;const a=s.userData?.gltfExtensions?.[br.WebGiLightExtrasExtension];a&&(!s.shadow&&a.shadow&&console.error("Light has no shadow, cannot import",s,a),a.shadow&&s.shadow&&(a.shadow.bias!==void 0&&(s.shadow.bias=a.shadow.bias),a.shadow.normalBias!==void 0&&(s.shadow.normalBias=a.shadow.normalBias),a.shadow.radius!==void 0&&(s.shadow.radius=a.shadow.radius),a.shadow.mapSize!==void 0&&s.shadow.mapSize.fromArray(a.shadow.mapSize),a.shadow.camera!==void 0&&(s.shadow.camera=new Lp().parseObject(a.shadow.camera,{},{},{},{}))),delete s.userData.gltfExtensions[br.WebGiLightExtrasExtension])})})}}),br.Export=e=>({writeNode:(t,i)=>{if(!t?.isLight)return;i.extensions||(i.extensions={});const n={};t.shadow&&(n.shadow=t.shadow.toJSON()),Object.keys(n).length>0&&(i.extensions[br.WebGiLightExtrasExtension]=n,e.extensionsUsed[br.WebGiLightExtrasExtension]=!0)}}),br.Textures=void 0;let Ed=br;const us=class us{};us.WebGiMaterialExtrasExtension="WEBGI_material_extras",us.Import=e=>t=>({name:"__"+us.WebGiMaterialExtrasExtension,afterRoot:async i=>{const n=i.scenes||(i.scene?[i.scene]:[]);for(const s of n){const a=s.userData?.gltfExtensions?.[us.WebGiMaterialExtrasExtension],o=a?.resources?await e(a.resources):{};s.traverse(l=>{const c=l?.material;if(!c?.isMaterial)return;const h=c.userData?.gltfExtensions?.[us.WebGiMaterialExtrasExtension];if(!h)return;h.emissiveIntensity!==void 0&&(c.emissiveIntensity=h.emissiveIntensity),h.fog!==void 0&&(c.fog=h.fog),h.flatShading!==void 0&&(c.flatShading=h.flatShading),h.blending!==void 0&&(c.blending=h.blending),h.side!==void 0&&(c.side=h.side),h.shadowSide!==void 0&&(c.shadowSide=h.shadowSide),h.depthFunc!==void 0&&(c.depthFunc=h.depthFunc),h.depthTest!==void 0&&(c.depthTest=h.depthTest),h.depthWrite!==void 0&&(c.depthWrite=h.depthWrite),h.colorWrite!==void 0&&(c.colorWrite=h.colorWrite),h.vertexColors!==void 0&&(c.vertexColors=h.vertexColors),h.alphaTest!==void 0&&(c.alphaTest=h.alphaTest),h.alphaHash!==void 0&&(c.alphaHash=h.alphaHash),h.envMapIntensity!==void 0&&(c.envMapIntensity=h.envMapIntensity),h.envMapRotation!==void 0&&Array.isArray(h.envMapRotation)&&c.envMapRotation?.fromArray&&c.envMapRotation.fromArray(h.envMapRotation),h.blendSrc!==void 0&&(c.blendSrc=h.blendSrc),h.blendDst!==void 0&&(c.blendDst=h.blendDst),h.blendEquation!==void 0&&(c.blendEquation=h.blendEquation),h.blendSrcAlpha!==void 0&&(c.blendSrcAlpha=h.blendSrcAlpha),h.blendDstAlpha!==void 0&&(c.blendDstAlpha=h.blendDstAlpha),h.blendEquationAlpha!==void 0&&(c.blendEquationAlpha=h.blendEquationAlpha),h.blendColor!==void 0&&c.blendColor!==void 0&&c.blendColor.setHex(h.blendColor),h.blendAlpha!==void 0&&(c.blendAlpha=h.blendAlpha),h.stencilWrite!==void 0&&(c.stencilWrite=h.stencilWrite),h.stencilWriteMask!==void 0&&(c.stencilWriteMask=h.stencilWriteMask),h.stencilFunc!==void 0&&(c.stencilFunc=h.stencilFunc),h.stencilRef!==void 0&&(c.stencilRef=h.stencilRef),h.stencilFuncMask!==void 0&&(c.stencilFuncMask=h.stencilFuncMask),h.stencilFail!==void 0&&(c.stencilFail=h.stencilFail),h.stencilZFail!==void 0&&(c.stencilZFail=h.stencilZFail),h.stencilZPass!==void 0&&(c.stencilZPass=h.stencilZPass),h.wireframe!==void 0&&(c.wireframe=h.wireframe),h.wireframeLinewidth!==void 0&&(c.wireframeLinewidth=h.wireframeLinewidth),h.wireframeLinecap!==void 0&&(c.wireframeLinecap=h.wireframeLinecap),h.wireframeLinejoin!==void 0&&(c.wireframeLinejoin=h.wireframeLinejoin),h.rotation!==void 0&&(c.rotation=h.rotation),h.linewidth!==void 0&&(c.linewidth=h.linewidth),h.worldUnits!==void 0&&(c.worldUnits=h.worldUnits),h.dashed!==void 0&&(c.dashed=h.dashed),h.dashSize!==void 0&&(c.dashSize=h.dashSize),h.dashScale!==void 0&&(c.dashScale=h.dashScale),h.dashOffset!==void 0&&(c.dashOffset=h.dashOffset),h.gapSize!==void 0&&(c.gapSize=h.gapSize),h.resolution!==void 0&&c.resolution&&c.resolution.fromArray&&c.resolution.fromArray(h.resolution),h.polygonOffset!==void 0&&(c.polygonOffset=h.polygonOffset),h.polygonOffsetFactor!==void 0&&(c.polygonOffsetFactor=h.polygonOffsetFactor),h.polygonOffsetUnits!==void 0&&(c.polygonOffsetUnits=h.polygonOffsetUnits),h.dithering!==void 0&&(c.dithering=h.dithering),h.alphaToCoverage!==void 0&&(c.alphaToCoverage=h.alphaToCoverage),h.premultipliedAlpha!==void 0&&(c.premultipliedAlpha=h.premultipliedAlpha),h.toneMapped!==void 0&&(c.toneMapped=h.toneMapped),h.normalScale!==void 0&&c.normalScale!==void 0&&(Array.isArray(h.normalScale)?c.normalScale.fromArray(h.normalScale):typeof h.normalScale=="number"?c.normalScale.set(h.normalScale,h.normalScale):console.warn("normalScale is not an array or number",h.normalScale)),h.reflectivity!==void 0&&(c.reflectivity=h.reflectivity),Object.entries(h).forEach(([d,p])=>{d.startsWith("_")||p&&p.resource&&typeof p.resource=="string"&&(c[d]=ke.Deserialize(p,c[d],o))}),delete c.userData.gltfExtensions[us.WebGiMaterialExtrasExtension];const u=t.json?.asset?.version?parseFloat(t.json?.asset?.version):null;(c.userData.legacyBumpScale||u&&u<=2)&&c?.bumpScale!==void 0&&c?.bumpMap&&c.defines&&(console.warn("MaterialManager: Old format material loaded, bump map might be incorrect.",c,c.bumpScale),c.defines.BUMP_MAP_SCALE_LEGACY="1",c.userData.legacyBumpScale=!0,c.needsUpdate=!0)}),a&&delete s.userData.gltfExtensions[us.WebGiMaterialExtrasExtension]}}}),us.Export=e=>({writeMaterial(t,i){if(!t?.isMaterial)return;i.extensions||(i.extensions={});const n={};t.fog!==void 0&&t.fog!==ai.MaterialProperties.fog&&(n.fog=t.fog),t.flatShading!==void 0&&t.flatShading!==ai.MaterialProperties.flatShading&&(n.flatShading=t.flatShading),t.blending!==void 0&&t.blending!==Et.blending&&(n.blending=t.blending),t.side!==void 0&&t.side!==Zi&&(n.side=t.side),t.shadowSide!==void 0&&t.shadowSide!==Et.shadowSide&&(n.shadowSide=t.shadowSide),t.depthFunc!==void 0&&t.depthFunc!==Et.depthFunc&&(n.depthFunc=t.depthFunc),t.depthTest!==void 0&&t.depthTest!==Et.depthTest&&(n.depthTest=t.depthTest),t.depthWrite!==void 0&&t.depthWrite!==Et.depthWrite&&(n.depthWrite=t.depthWrite),t.colorWrite!==void 0&&t.colorWrite!==Et.colorWrite&&(n.colorWrite=t.colorWrite),t.vertexColors!==void 0&&t.vertexColors!==Et.vertexColors&&(n.vertexColors=t.vertexColors),t.alphaTest!==void 0&&t.alphaTest!==Et.alphaTest&&(n.alphaTest=t.alphaTest),t.alphaHash!==void 0&&t.alphaHash!==Et.alphaHash&&(n.alphaHash=t.alphaHash),t.envMapIntensity!==void 0&&t.envMapIntensity!==ai.MaterialProperties.envMapIntensity&&(n.envMapIntensity=t.envMapIntensity),t.envMapRotation!==void 0&&!t.envMapRotation.equals(ai.MaterialProperties.envMapRotation)&&(n.envMapRotation=t.envMapRotation.toArray()),t.blendSrc!==void 0&&t.blendSrc!==Et.blendSrc&&(n.blendSrc=t.blendSrc),t.blendDst!==void 0&&t.blendDst!==Et.blendDst&&(n.blendDst=t.blendDst),t.blendEquation!==void 0&&t.blendEquation!==Et.blendEquation&&(n.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&t.blendSrcAlpha!==Et.blendSrcAlpha&&(n.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&t.blendDstAlpha!==Et.blendDstAlpha&&(n.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&t.blendEquationAlpha!==Et.blendEquationAlpha&&(n.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&t.blendColor!==Et.blendColor&&(n.blendColor=t.blendColor.getHex()),t.blendAlpha!==void 0&&t.blendAlpha!==Et.blendAlpha&&(n.blendAlpha=t.blendAlpha),t.stencilWrite!==void 0&&t.stencilWrite!==Et.stencilWrite&&(n.stencilWrite=t.stencilWrite),t.stencilWriteMask!==void 0&&t.stencilWriteMask!==Et.stencilWriteMask&&(n.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&t.stencilFunc!==Et.stencilFunc&&(n.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&t.stencilRef!==Et.stencilRef&&(n.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&t.stencilFuncMask!==Et.stencilFuncMask&&(n.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&t.stencilFail!==Et.stencilFail&&(n.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&t.stencilZFail!==Et.stencilZFail&&(n.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&t.stencilZPass!==Et.stencilZPass&&(n.stencilZPass=t.stencilZPass),t.wireframe!==void 0&&t.wireframe!==ai.MaterialProperties.wireframe&&(n.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&t.wireframeLinewidth!==ai.MaterialProperties.wireframeLinewidth&&(n.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&t.wireframeLinecap!==ai.MaterialProperties.wireframeLinecap&&(n.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&t.wireframeLinejoin!==ai.MaterialProperties.wireframeLinejoin&&(n.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(n.rotation=t.rotation),t.linewidth!==void 0&&t.linewidth!==ji.MaterialProperties.linewidth&&(n.linewidth=t.linewidth),t.worldUnits!==void 0&&t.worldUnits!==ji.MaterialProperties.worldUnits&&(n.worldUnits=t.worldUnits),t.dashed!==void 0&&t.dashed!==ji.MaterialProperties.dashed&&(n.dashed=t.dashed),t.dashSize!==void 0&&t.dashSize!==ji.MaterialProperties.dashSize&&(n.dashSize=t.dashSize),t.dashScale!==void 0&&t.dashScale!==ji.MaterialProperties.dashScale&&(n.dashScale=t.dashScale),t.dashOffset!==void 0&&t.dashOffset!==ji.MaterialProperties.dashOffset&&(n.dashOffset=t.dashOffset),t.gapSize!==void 0&&t.gapSize!==ji.MaterialProperties.gapSize&&(n.gapSize=t.gapSize),t.polygonOffset!==void 0&&t.polygonOffset!==Et.polygonOffset&&(n.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&t.polygonOffsetFactor!==Et.polygonOffsetFactor&&(n.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&t.polygonOffsetUnits!==Et.polygonOffsetUnits&&(n.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&t.dithering!==Et.dithering&&(n.dithering=t.dithering),t.alphaToCoverage!==void 0&&t.alphaToCoverage!==Et.alphaToCoverage&&(n.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&t.premultipliedAlpha!==Et.premultipliedAlpha&&(n.premultipliedAlpha=t.premultipliedAlpha),t.toneMapped!==void 0&&t.toneMapped!==Et.toneMapped&&(n.toneMapped=t.toneMapped),t.normalScale!==void 0&&t.normalScale.isVector2&&(t.normalScale.x!==ai.MaterialProperties.normalScale.x||t.normalScale.y!==ai.MaterialProperties.normalScale.y)&&(n.normalScale=[t.normalScale.x,t.normalScale.y]);const s=this.materialExternalResources[t.uuid];s&&Object.entries(s).forEach(([a,o])=>{if(a.startsWith("_"))return;let l=!1;o?.userData&&o.userData.embedUrlImagePreviews===void 0&&(o.userData.embedUrlImagePreviews=e.options.exporterOptions?.embedUrlImagePreviews,l=!0),n[a]=ke.Serialize(o,this.serializedMeta),o?.userData&&l&&delete o.userData.embedUrlImagePreviews}),Object.keys(n).length>0&&(i.extensions[us.WebGiMaterialExtrasExtension]=n,e.extensionsUsed[us.WebGiMaterialExtrasExtension]=!0)},materialExternalResources:{},serializedMeta:{images:{},textures:{}},beforeParse(t){if(this.materialExternalResources={},!e.options.externalImagesInExtras)return;const i=[];(Array.isArray(t)?t:[t]).forEach(n=>{n?.traverse(s=>{s&&s.material?.isMaterial&&i.push(s.material)})}),i.forEach(n=>{n&&(this.materialExternalResources[n.uuid]||(this.materialExternalResources[n.uuid]={}),this.materialExternalResources[n.uuid].__materialRef=n,Object.entries(n).forEach(([s,a])=>{s.startsWith("_")||a&&a.isTexture&&a.userData.rootPath&&Hc(a.userData.rootPath)&&(n[s]=null,this.materialExternalResources[n.uuid][s]=a)}))})},afterParse(t){const i=Object.values(this.materialExternalResources);if(i.length<1)return;i.forEach(s=>{const a=s.__materialRef;a&&(Object.entries(s).forEach(([o,l])=>{o.startsWith("_")||l&&(a[o]=l)}),delete this.materialExternalResources[a.uuid])});const n=e.json.scenes[e.json.scene||0];n.extensions||(n.extensions={}),n.extensions[us.WebGiMaterialExtrasExtension]={resources:this.serializedMeta},e.extensionsUsed[us.WebGiMaterialExtrasExtension]=!0}}),us.Textures=void 0;let Md=us;const Nh=class Nh{};Nh.WebGiMaterialsAlphaMapExtension="WEBGI_materials_alphamap",Nh.Import=e=>new Zk(e),Nh.Export=e=>new eG(e),Nh.Textures={alphaTexture:"G"};let wl=Nh;class Zk{constructor(e){this.parser=e,this.name=wl.WebGiMaterialsAlphaMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.alphaTexture!==void 0&&s.push(i.assignTexture(t,"alphaMap",a.alphaTexture)),Promise.all(s)}}class eG{constructor(e){this.writer=e,this.name=wl.WebGiMaterialsAlphaMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||!e.alphaMap)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.alphaMap&&i.checkEmptyMap(e.alphaMap)){const a={index:i.processTexture(e.alphaMap)};i.applyTextureTransform(a,e.alphaMap),s.alphaTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const kh=class kh{};kh.WebGiMaterialsBumpMapExtension="WEBGI_materials_bumpmap",kh.Import=e=>new tG(e),kh.Export=e=>new iG(e),kh.Textures={bumpTexture:"R"};let rh=kh;class tG{constructor(e){this.parser=e,this.name=rh.WebGiMaterialsBumpMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.bumpScale!==void 0&&(t.bumpScale=a.bumpScale),a.bumpTexture!==void 0&&s.push(i.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(s)}}class iG{constructor(e){this.writer=e,this.name=rh.WebGiMaterialsBumpMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.bumpScale===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.bumpScale!==ai.MaterialProperties.bumpScale&&(s.bumpScale=e.bumpScale),e.bumpMap&&i.checkEmptyMap(e.bumpMap)){const a={index:i.processTexture(e.bumpMap)};i.applyTextureTransform(a,e.bumpMap),s.bumpTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const Gh=class Gh{};Gh.WebGiMaterialsDisplacementMapExtension="WEBGI_materials_displacementmap",Gh.Import=e=>new nG(e),Gh.Export=e=>new sG(e),Gh.Textures={displacementTexture:"R"};let Cl=Gh;class nG{constructor(e){this.parser=e,this.name=Cl.WebGiMaterialsDisplacementMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.displacementScale!==void 0&&(t.displacementScale=a.displacementScale),a.displacementBias!==void 0&&(t.displacementBias=a.displacementBias),a.displacementTexture!==void 0&&s.push(i.assignTexture(t,"displacementMap",a.displacementTexture)),Promise.all(s)}}class sG{constructor(e){this.writer=e,this.name=Cl.WebGiMaterialsDisplacementMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.displacementScale===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.displacementScale!==ai.MaterialProperties.displacementScale&&(s.displacementScale=e.displacementScale),e.displacementBias!==ai.MaterialProperties.displacementBias&&(s.displacementBias=e.displacementBias),e.displacementMap&&i.checkEmptyMap(e.displacementMap)){const a={index:i.processTexture(e.displacementMap)};i.applyTextureTransform(a,e.displacementMap),s.displacementTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const zh=class zh{};zh.WebGiMaterialsLightMapExtension="WEBGI_materials_lightmap",zh.Import=e=>new rG(e),zh.Export=e=>new aG(e),zh.Textures={lightMapTexture:"RGB"};let xl=zh;class rG{constructor(e){this.parser=e,this.name=xl.WebGiMaterialsLightMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.lightMapIntensity!==void 0&&(t.lightMapIntensity=a.lightMapIntensity),a.lightMapTexture!==void 0&&s.push(i.assignTexture(t,"lightMap",a.lightMapTexture)),Promise.all(s)}}class aG{constructor(e){this.writer=e,this.name=xl.WebGiMaterialsLightMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.lightMapIntensity===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.lightMapIntensity!==ai.MaterialProperties.lightMapIntensity&&(s.lightMapIntensity=e.lightMapIntensity),e.lightMap&&i.checkEmptyMap(e.lightMap)){const a={index:i.processTexture(e.lightMap)};i.applyTextureTransform(a,e.lightMap),s.lightMapTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const wr=class wr{};wr.WebGiObject3DExtrasExtension="WEBGI_object3d_extras",wr.Import=e=>({name:"__"+wr.WebGiObject3DExtrasExtension,afterRoot:async t=>{(t.scenes||(t.scene?[t.scene]:[])).forEach(n=>{n.traverse(s=>{if(!s||!s.isObject3D)return;const a=s.userData?.gltfExtensions?.[wr.WebGiObject3DExtrasExtension];if(!a){s.isLight&&!s.isAmbientLight&&(s.castShadow=!0);return}s.castShadow=a.castShadow??!1,s.receiveShadow=a.receiveShadow??!1,a.visible!==void 0&&(s.visible=a.visible),a.frustumCulled!==void 0&&(s.frustumCulled=a.frustumCulled),a.renderOrder!==void 0&&(s.renderOrder=a.renderOrder),a.layers!==void 0&&(s.layers.mask=a.layers),s.userData.__keepShadowDef=!0,delete s.userData.gltfExtensions[wr.WebGiObject3DExtrasExtension]})})}}),wr.Export=e=>({writeNode:(t,i)=>{if(!t?.isObject3D)return;i.extensions||(i.extensions={});const n={};t.castShadow!==void 0&&t.castShadow&&(n.castShadow=t.castShadow),t.receiveShadow!==void 0&&t.receiveShadow&&(n.receiveShadow=t.receiveShadow),t.visible===!1&&(n.visible=!1),t.frustumCulled===!1&&(n.frustumCulled=!1),t.renderOrder!==0&&(n.renderOrder=t.renderOrder),t.layers.mask!==1&&(n.layers=t.layers.mask),t.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),Object.keys(n).length>0&&(i.extensions[wr.WebGiObject3DExtrasExtension]=n,e.extensionsUsed[wr.WebGiObject3DExtrasExtension]=!0)}}),wr.Textures=void 0;let Td=wr;class sT extends Zt{constructor(e){super(e),this.type=$t}async loadAsync(e,t){const i=await this.parseAsync(e,t,!1),n=new As(i.data,i.width,i.height,Kt,this.type);return n.needsUpdate=!0,n.flipY=!0,n.colorSpace=vt,n.minFilter=st,n.magFilter=st,n.source.data.complete=!0,n}async parseAsync(e,t,i=!1){let n=!1;if(!e.startsWith("data:")&&!e.startsWith("blob:")){this.responseType="blob";const l=await super.loadAsync(e,t);e=URL.createObjectURL(l),n=!0}const s=await rS(e);n&&URL.revokeObjectURL(e);let a=Uint8Array;return this.type===$t?a=Uint16Array:this.type===zt&&(a=Float32Array),{data:oG(s.data,4,a,i),width:s.width,height:s.height}}setDataType(e){return this.type=e,this}}function oG(r,e=3,t=Uint16Array,i=!1){let n;const s=r.byteLength>>2,a=new t(s*e);for(let o=0;o<s;o++)n=Math.pow(2,r[o*4+3]-136),i?(a[o*e]=Math.min(r[o*4]*n,65504),a[o*e+1]=Math.min(r[o*4+1]*n,65504),a[o*e+2]=Math.min(r[o*4+2]*n,65504)):(a[o*e]=Hn.toHalfFloat(Math.min(r[o*4]*n,65504)),a[o*e+1]=Hn.toHalfFloat(Math.min(r[o*4+1]*n,65504)),a[o*e+2]=Hn.toHalfFloat(Math.min(r[o*4+2]*n,65504))),e===4&&(a[o*e+3]=Hn.toHalfFloat(1));return a}const Zd=class Zd{static async ImportViewerConfig(e,t,i,n){if(!n){const l=e.json.scenes||[];if(l.length!==1){for(const c of l){const h=l.indexOf(c);await this.ImportViewerConfig(e,t,h>=0?[i[h]]:i,c)}return{}}n=l[0]}const s=i.length>0?i[0]:void 0,a=n.extensions?.[this.ViewerConfigGLTFExtension];if(!a)return{};const o={type:"ThreeViewer",version:"0",plugins:[],assetType:"config",...a};return o.resources&&(o.resources=await this.ImportResources(o.resources,e,t)),s&&(s.importedViewerConfig=o),o}static async ImportResources(e,t,i){if(e.__isLoadedResources)return e;await this._parseArrayBuffers(e,t);const n=await this._parseExtraResources(e,t,i);return await i.loadConfigResources(e||{},n)}static async _parseExtraResources(e,t,i){const n={textures:{},materials:{}};if(e.textures&&t.json.textures)for(const[s,a]of[...Object.entries(e.textures)]){if(a.uuid||!s)continue;delete e.textures[s];const o=t.json.textures.findIndex(l=>l.extras?.uuid===s||t.json.samplers?.[l.sampler]?.extras?.uuid===s||t.json.images?.[l.source]?.extras?.t_uuid===s);o>=0&&(n.textures[s]=await t.getDependency("texture",o))}if(e.materials&&t.json.materials)for(const[s,a]of[...Object.entries(e.materials)]){if(a.uuid||!s)continue;delete e.materials[s];const o=t.json.materials.findIndex(l=>l.extras?.uuid===s);if(o>=0){const l=await t.getDependency("material",o);n.materials[s]=i.assetManager.materials.convertToIMaterial(l)}}return n}static async _parseArrayBuffers(e,t){const i=[];Object.values(e).forEach(n=>{Object.values(n).forEach(s=>{s.url&&(s.url.type==="Uint16Array"&&s.url.data&&i.push(s.url),s.url.type==="Uint8Array"&&s.url.data&&i.push(s.url))})});for(const n of i){const s=n.data.image,a=t.json.images[s],o=await t.getDependency("bufferView",a.bufferView);if(a.mimeType.startsWith("image/")&&n.type==="Uint16Array"&&n.encoding==="rgbe"){const l=new Blob([o]);let c=URL.createObjectURL(l);const h=n.encodingVersion||1;h<2&&(c="data:image/png;base64,"+btoa(await l.text())),n.data=(await new sT().parseAsync(c,void 0,h<3)).data,URL.revokeObjectURL(c),delete n.encoding,delete n.encodingVersion}else n.data=o}}static ExportViewerConfig(e,t){const n=Object.entries(t.serializationMeta).reduce((l,c)=>l+(c[0].startsWith("_")?0:Object.keys(c[1]).length),0)?t.serializationMeta:void 0,s=e.toJSON(!0,void 0,n),a=t.json.scenes[t.json.scene||0];a.extensions||(a.extensions={}),t.extensionsUsed[this.ViewerConfigGLTFExtension]=!0,a.extensions[this.ViewerConfigGLTFExtension]=s;const o=s.resources;if(o&&(Zd.BundleExtraResources(t.json,o),Zd.BundleArrayBuffers(o,t),n))return delete s.resources,o}static BundleArrayBuffers(e,t){const i=[];Object.entries(e).forEach(([n,s])=>{n.startsWith("_")||s&&Object.values(s).forEach(a=>{a.url&&(a.url.type==="Uint16Array"&&a.url.data&&(a.url.data instanceof Uint16Array||(a.url.data=new Uint16Array(a.url.data)),i.push(a.url)),a.url.type==="Uint8Array"&&a.url.data&&(a.url.data instanceof Uint8Array||(a.url.data=new Uint8Array(a.url.data)),i.push(a.url)))})});for(const n of i){let s="application/octet-stream";if(n.mimeType&&(s=n.mimeType),t.options.exporterOptions.encodeUint16Rgbe&&n.type==="Uint16Array"&&n.width>0&&n.height>0){const u=VS(n.data,4),d=new ImageData(u,n.width,n.height),p=PA.getDataURL(d,!0).split(",")[1];s="image/png",n.data=Uint8Array.from(atob(p),m=>m.charCodeAt(0)),n.encoding="rgbe",n.encodingVersion=3}t.json.images||(t.json.images=[]);const o={mimeType:s},l=t.json.images.push(o)-1,c=n.data;o.bufferView=t.processBufferViewImageBuffer(c),n.data={image:l}}}static BundleExtraResources(e,t){const{textures:i,materials:n}=t;e.textures&&e.samplers&&e.images&&i&&[...Object.entries(i)].forEach(([s,a])=>{e.textures.find(l=>l.extras?.uuid===s||e.samplers[l.sampler]?.extras?.uuid===s||e.images[l.source]?.extras?.t_uuid===s)&&(a.image&&t.images&&t.images[a.image]&&delete t.images[a.image],i[s]={})}),e.materials&&n&&[...Object.entries(n)].forEach(([s,a])=>{e.materials.find(l=>l.extras?.uuid===s)&&(n[s]={})})}};Zd.ViewerConfigGLTFExtension="WEBGI_viewer";let fo=Zd;class xt extends li{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new dG(t)}),this.register(function(t){return new bG(t)}),this.register(function(t){return new wG(t)}),this.register(function(t){return new CG(t)}),this.register(function(t){return new pG(t)}),this.register(function(t){return new mG(t)}),this.register(function(t){return new gG(t)}),this.register(function(t){return new AG(t)}),this.register(function(t){return new uG(t)}),this.register(function(t){return new yG(t)}),this.register(function(t){return new fG(t)}),this.register(function(t){return new _G(t)}),this.register(function(t){return new vG(t)}),this.register(function(t){return new cG(t)}),this.register(function(t){return new xG(t)}),this.register(function(t){return new SG(t)})}load(e,t,i,n){const s=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const c=Rs.extractUrlBase(e);a=Rs.resolveURL(c,this.path)}else a=Rs.extractUrlBase(e);this.manager.itemStart(e);const o=function(c){n?n(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new Zt(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(h){t(h),s.manager.itemEnd(e)},o,e)}catch(h){o(h)}},i,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,n,s){let a;const o={},l={},c=new TextDecoder;if(typeof e=="string")a=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===rT){try{o[Ht.KHR_BINARY_GLTF]=new w0(e)}catch(d){n&&n(d);return}a=JSON.parse(o[Ht.KHR_BINARY_GLTF].content)}else a=JSON.parse(c.decode(e));else a=e;if(a.asset===void 0||a.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new hT(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const d=this.pluginCallbacks[u](h);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[d.name]=d,o[d.name]=!0}if(a.extensionsUsed)for(let u=0;u<a.extensionsUsed.length;++u){const d=a.extensionsUsed[u],p=a.extensionsRequired||[];switch(d){case Ht.KHR_MATERIALS_UNLIT:o[d]=new hG;break;case Ht.KHR_DRACO_MESH_COMPRESSION:o[d]=new EG(a,this.dracoLoader);break;case Ht.KHR_TEXTURE_TRANSFORM:o[d]=new MG;break;case Ht.KHR_MESH_QUANTIZATION:o[d]=new TG;break;default:p.indexOf(d)>=0&&l[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}h.setExtensions(o),h.setPlugins(l),h.parse(i,n)}parseAsync(e,t){const i=this;return new Promise(function(n,s){i.parse(e,t,n,s)})}}xt.ObjectConstructors={DirectionalLight:il,PointLight:tl,SpotLight:zc,MeshStandardMaterial:Ka,MeshBasicMaterial:ss,MeshPhysicalMaterial:Nc,LineBasicMaterial:Ei,PointsMaterial:Tr,PerspectiveCamera:Vi,OrthographicCamera:Mr};function lG(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}const Ht={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class cG{constructor(e){this.parser=e,this.name=Ht.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,n=t.length;i<n;i++){const s=t[i];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let n=t.cache.get(i);if(n)return n;const s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let c;const h=new se(16777215);l.color!==void 0&&h.setRGB(l.color[0],l.color[1],l.color[2],Dt);const u=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new xt.ObjectConstructors.DirectionalLight(h),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new xt.ObjectConstructors.PointLight(h),c.distance=u;break;case"spot":c=new xt.ObjectConstructors.SpotLight(h),c.distance=u,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),c.decay=2,kr(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),n=Promise.resolve(c),t.cache.add(i,n),n}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,s=i.json.nodes[e],o=(s.extensions&&s.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return i._getNodeRef(t.cache,o,l)})}}class hG{constructor(){this.name=Ht.KHR_MATERIALS_UNLIT}getMaterialType(){return xt.ObjectConstructors.MeshBasicMaterial}extendParams(e,t,i){const n=[];e.color=new se(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const a=s.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],Dt),e.opacity=a[3]}s.baseColorTexture!==void 0&&n.push(i.assignTexture(e,"map",s.baseColorTexture,vt))}return Promise.all(n)}}class uG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=n.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class dG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&s.push(i.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&s.push(i.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(s.push(i.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new $(o,o)}return Promise.all(s)}}class fG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&s.push(i.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&s.push(i.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(s)}}class pG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_SHEEN}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new se(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=n.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],Dt)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&s.push(i.assignTexture(t,"sheenColorMap",a.sheenColorTexture,vt)),a.sheenRoughnessTexture!==void 0&&s.push(i.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),n.extras&&n.extras.sheenFactor!==void 0&&(t.sheen=n.extras.sheenFactor,delete n.extras.sheenFactor),Promise.all(s)}}class mG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&s.push(i.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(s)}}class gG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_VOLUME}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&s.push(i.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new se().setRGB(o[0],o[1],o[2],Dt),Promise.all(s)}}class AG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_IOR}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=n.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class yG{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_SPECULAR}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&s.push(i.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new se().setRGB(o[0],o[1],o[2],Dt),a.specularColorTexture!==void 0&&s.push(i.assignTexture(t,"specularColorMap",a.specularColorTexture,vt)),Promise.all(s)}}class vG{constructor(e){this.parser=e,this.name=Ht.EXT_MATERIALS_BUMP}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&s.push(i.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(s)}}class _G{constructor(e){this.parser=e,this.name=Ht.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:xt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&s.push(i.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(s)}}class bG{constructor(e){this.parser=e,this.name=Ht.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,i=t.json,n=i.textures[e];if(!n.extensions||!n.extensions[this.name])return null;const s=n.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}}class wG{constructor(e){this.parser=e,this.name=Ht.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,n=i.json,s=n.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=n.images[a.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return i.loadTextureImage(e,a.source,l);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return i.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class CG{constructor(e){this.parser=e,this.name=Ht.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,n=i.json,s=n.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=n.images[a.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return i.loadTextureImage(e,a.source,l);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return i.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class xG{constructor(e){this.name=Ht.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const n=i.extensions[this.name],s=this.parser.getDependency("buffer",n.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){const l=n.byteOffset||0,c=n.byteLength||0,h=n.count,u=n.byteStride,d=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,d,n.mode,n.filter).then(function(p){return p.buffer}):a.ready.then(function(){const p=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(p),h,u,d,n.mode,n.filter),p})})}else return null}}class SG{constructor(e){this.name=Ht.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const n=t.meshes[i.mesh];for(const c of n.primitives)if(c.mode!==Ws.TRIANGLES&&c.mode!==Ws.TRIANGLE_STRIP&&c.mode!==Ws.TRIANGLE_FAN&&c.mode!==void 0)return null;const a=i.extensions[this.name].attributes,o=[],l={};for(const c in a)o.push(this.parser.getDependency("accessor",a[c]).then(h=>(l[c]=h,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const h=c.pop(),u=h.isGroup?h.children:[h],d=c[0].count,p=[];for(const m of u){const A=new pe,g=new x,y=new Qe,_=new x(1,1,1),v=new Bc(m.geometry,m.material,d);for(let b=0;b<d;b++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,b),l.ROTATION&&y.fromBufferAttribute(l.ROTATION,b),l.SCALE&&_.fromBufferAttribute(l.SCALE,b),v.setMatrixAt(b,A.compose(g,y,_));v.sourceTrs=l;for(const b in l)if(b==="_COLOR_0"){const T=l[b];v.instanceColor=new ha(T.array,T.itemSize,T.normalized)}else b!=="TRANSLATION"&&b!=="ROTATION"&&b!=="SCALE"&&m.geometry.setAttribute(b,l[b]);ft.prototype.copy.call(v,m),this.parser.assignFinalMaterial(v),p.push(v)}return h.isGroup?(h.clear(),h.add(...p),h):p[0]}))}}const rT="glTF",Id=12,aT={JSON:1313821514,BIN:5130562};class w0{constructor(e){this.name=Ht.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Id),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==rT)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-Id,s=new DataView(e,Id);let a=0;for(;a<n;){const o=s.getUint32(a,!0);a+=4;const l=s.getUint32(a,!0);if(a+=4,l===aT.JSON){const c=new Uint8Array(e,Id+a,o);this.content=i.decode(c)}else if(l===aT.BIN){const c=Id+a;this.body=e.slice(c,c+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class EG{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Ht.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,n=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const h in a){const u=x0[h]||h.toLowerCase();o[u]=a[h]}for(const h in e.attributes){const u=x0[h]||h.toLowerCase();if(a[h]!==void 0){const d=i.accessors[e.attributes[h]],p=ah[d.componentType];c[u]=p.name,l[u]=d.normalized===!0}}return t.getDependency("bufferView",s).then(function(h){return new Promise(function(u,d){n.decodeDracoFile(h,function(p){for(const m in p.attributes){const A=p.attributes[m],g=l[m];g!==void 0&&(A.normalized=g)}u(p)},o,c,Dt,d)})})}}class MG{constructor(){this.name=Ht.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e.__hasGLTFUuid||(e=e.clone()),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class TG{constructor(){this.name=Ht.KHR_MESH_QUANTIZATION}}class oT extends kc{constructor(e,t,i,n){super(e,t,i,n)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,s=e*n*3+n;for(let a=0;a!==n;a++)t[a]=i[s+a];return t}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,h=n-t,u=(i-t)/h,d=u*u,p=d*u,m=e*c,A=m-c,g=-2*p+3*d,y=p-d,_=1-g,v=y-d+u;for(let b=0;b!==o;b++){const T=a[A+b+o],E=a[A+b+l]*h,M=a[m+b+o],S=a[m+b]*h;s[b]=_*T+v*E+g*M+y*S}return s}}const IG=new Qe;class PG extends oT{interpolate_(e,t,i,n){const s=super.interpolate_(e,t,i,n);return IG.fromArray(s).normalize().toArray(s),s}}const Ws={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},ah={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},lT={9728:pi,9729:st,9984:Jh,9985:Po,9986:Na,9987:Ln},cT={33071:ui,33648:Zr,10497:Bn},C0={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},x0={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},po={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},DG={CUBICSPLINE:void 0,LINEAR:Ro,STEP:Jl},S0={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function RG(r){return r.DefaultMaterial===void 0&&(r.DefaultMaterial=new xt.ObjectConstructors.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:fs})),r.DefaultMaterial}function xa(r,e,t){for(const i in t.extensions)r[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function kr(r,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(r.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function BG(r,e,t){let i=!1,n=!1,s=!1;for(let c=0,h=e.length;c<h;c++){const u=e[c];if(u.POSITION!==void 0&&(i=!0),u.NORMAL!==void 0&&(n=!0),u.COLOR_0!==void 0&&(s=!0),i&&n&&s)break}if(!i&&!n&&!s)return Promise.resolve(r);const a=[],o=[],l=[];for(let c=0,h=e.length;c<h;c++){const u=e[c];if(i){const d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):r.attributes.position;a.push(d)}if(n){const d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):r.attributes.normal;o.push(d)}if(s){const d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):r.attributes.color;l.push(d)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){const h=c[0],u=c[1],d=c[2];return i&&(r.morphAttributes.position=h),n&&(r.morphAttributes.normal=u),s&&(r.morphAttributes.color=d),r.morphTargetsRelative=!0,r})}function LG(r,e){if(r.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)r.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(r.morphTargetInfluences.length===t.length){r.morphTargetDictionary={};for(let i=0,n=t.length;i<n;i++)r.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function OG(r){let e;const t=r.extensions&&r.extensions[Ht.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+E0(t.attributes):e=r.indices+":"+E0(r.attributes)+":"+r.mode,r.targets!==void 0)for(let i=0,n=r.targets.length;i<n;i++)e+=":"+E0(r.targets[i]);return e}function E0(r){let e="";const t=Object.keys(r).sort();for(let i=0,n=t.length;i<n;i++)e+=t[i]+":"+r[t[i]]+";";return e}function M0(r){switch(r){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function UG(r){return r.search(/\.jpe?g($|\?)/i)>0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const FG=new pe;class hT{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new lG,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,n=!1,s=-1;typeof navigator<"u"&&(i=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,n=navigator.userAgent.indexOf("Firefox")>-1,s=n?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||i||n&&s<98?this.textureLoader=new to(this.options.manager):this.textureLoader=new gx(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Zt(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,n=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(a){const o={scene:a[0][n.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:n.asset,parser:i,userData:{}};return xa(s,o,n),kr(o,n),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let n=0,s=t.length;n<s;n++){const a=t[n].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let n=0,s=e.length;n<s;n++){const a=e[n];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(i[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;const n=i.clone(),s=(a,o)=>{const l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(const[c,h]of a.children.entries())s(h,o.children[c])};return s(i,n),n.name+="_instance_"+e.uses[t]++,n}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const n=e(t[i]);if(n)return n}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let n=0;n<t.length;n++){const s=e(t[n]);s&&i.push(s)}return i}getDependency(e,t){const i=e+":"+t;let n=this.cache.get(i);if(!n){switch(e){case"scene":n=this.loadScene(t);break;case"node":n=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":n=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!n)throw new Error("Unknown type: "+e);break}this.cache.add(i,n)}return n}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,n=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(n.map(function(s,a){return i.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Ht.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(s,a){i.load(Rs.resolveURL(t.uri,n.path),s,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){const n=t.byteLength||0,s=t.byteOffset||0;return i.slice(s,s+n)})}loadAccessor(e){const t=this,i=this.json,n=this.json.accessors[e];if(n.bufferView===void 0&&n.sparse===void 0){const a=C0[n.type],o=ah[n.componentType],l=n.normalized===!0,c=new o(n.count*a);return Promise.resolve(new Xe(c,a,l))}const s=[];return n.bufferView!==void 0?s.push(this.getDependency("bufferView",n.bufferView)):s.push(null),n.sparse!==void 0&&(s.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(s).then(function(a){const o=a[0],l=C0[n.type],c=ah[n.componentType],h=c.BYTES_PER_ELEMENT,u=h*l,d=n.byteOffset||0,p=n.bufferView!==void 0?i.bufferViews[n.bufferView].byteStride:void 0,m=n.normalized===!0;let A,g;if(p&&p!==u){const y=Math.floor(d/p),_="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+y+":"+n.count;let v=t.cache.get(_);v||(A=new c(o,y*p,n.count*p/h),v=new Sc(A,p/h),t.cache.add(_,v)),g=new On(v,l,d%p/h,m)}else o===null?A=new c(n.count*l):A=new c(o,d,n.count*l),g=new Xe(A,l,m);if(n.sparse!==void 0){const y=C0.SCALAR,_=ah[n.sparse.indices.componentType],v=n.sparse.indices.byteOffset||0,b=n.sparse.values.byteOffset||0,T=new _(a[1],v,n.sparse.count*y),E=new c(a[2],b,n.sparse.count*l);o!==null&&(g=new Xe(g.array.slice(),g.itemSize,g.normalized));for(let M=0,S=T.length;M<S;M++){const w=T[M];if(g.setX(w,E[M*l]),l>=2&&g.setY(w,E[M*l+1]),l>=3&&g.setZ(w,E[M*l+2]),l>=4&&g.setW(w,E[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return g})}loadTexture(e){const t=this.json,i=this.options;if(e<0||e>=t.textures.length)return console.warn("THREE.GLTFLoader: Invalid texture index:",e),null;const s=t.textures[e].source;if(s<0||s>=t.images.length)return console.warn("THREE.GLTFLoader: Invalid source index:",s),null;const a=t.images[s];let o=this.textureLoader;if(a.uri){const l=i.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,i){const n=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(h){h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);const d=(s.samplers||{})[a.sampler]||{};return h.magFilter=lT[d.magFilter]||st,h.minFilter=lT[d.minFilter]||Ln,h.wrapS=cT[d.wrapS]||Bn,h.wrapT=cT[d.wrapT]||Bn,d.extras&&d.extras.uuid!==void 0&&(h.uuid=d.extras.uuid,h.__hasGLTFUuid=!0),n.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t,i=!1,n=!1){const s=this,a=this.json,o=this.options;if(!n&&this.sourceCache[e]!==void 0)return this.sourceCache[e].then(m=>m.clone());const l=a.images[e],c=self.URL||self.webkitURL;l.uri===void 0&&l.extras&&l.extras.uri&&(l.uri=l.extras.uri);let h=l.uri||"",u=!1,d=null;if(l.bufferView!==void 0&&(!i||!h))h=s.getDependency("bufferView",l.bufferView).then(function(m){u=!0;const A=new Blob([m],{type:l.mimeType});return h=c.createObjectURL(A),d=A,h});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const p=Promise.resolve(h).then(function(m){return new Promise(function(A,g){let y=A;t.isImageBitmapLoader===!0&&(y=function(_){const v=new Rt(_);v.needsUpdate=!0,A(v)}),t.load(Rs.resolveURL(m,o.path),y,void 0,function(_){t.isImageBitmapLoader===!0?(t=new to(s.options.manager),y=A,t.setCrossOrigin(s.options.crossOrigin),t.setRequestHeader(s.options.requestHeader),t.load(Rs.resolveURL(m,o.path),y,void 0,g)):g(_)})})}).then(function(m){if(u===!0&&c.revokeObjectURL(h),m.userData.mimeType=l.mimeType||UG(l.uri),m.flipY=!1,l.extras){if(l.extras.flipY!==void 0){if(t.isImageBitmapLoader===!0&&typeof createImageBitmap!==void 0){let A=m;const g=l.extras.flipY&&!A.flipY;createImageBitmap(A.source.data,{imageOrientation:g?"flipY":"none"}).then(function(y){A._newTex&&(A=A._newTex),A.source.data.close&&A.source.data.close(),A.source.data=y,A.source.needsUpdate=!0,A.needsUpdate=!0})}m.flipY=l.extras.flipY,m.needsUpdate=!0,delete l.extras.flipY}l.extras.uuid!==void 0&&(m.source.uuid=l.extras.uuid),l.extras.t_uuid!==void 0&&(m.uuid=l.extras.t_uuid,m.__hasGLTFUuid=!0)}return l.uri&&typeof l.uri=="string"&&u===!1&&(m.userData.rootPath=Rs.resolveURL(l.uri,o.path)),d&&(m.userData.__sourceBlob=d),!i&&l.uri&&l.uri!==h&&s.loadImageSource(e,t,!0,!0).then(function(A){m.source.data&&m.source.data.close&&m.source.data.close(),m.dispose(),m.source=A.source,m.source.needsUpdate=!0,m.needsUpdate=!0,m.uuid=A.uuid,A.__hasGLTFUuid&&(m.__hasGLTFUuid=!0),m.flipY=A.flipY,m.userData=A.userData,m.setDirty&&m.setDirty(),A._newTex=m}),m}).catch(function(m){throw console.error("THREE.GLTFLoader: Couldn't load texture",h),m});return this.sourceCache[e]=p,p}assignTexture(e,t,i,n){const s=this;return this.getDependency("texture",i.index).then(function(a){if(!a)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(a=a.clone(),a.channel=i.texCoord),s.extensions[Ht.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[Ht.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=s.associations.get(a);a=s.extensions[Ht.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return n!==void 0&&(a.colorSpace=n),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const n=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+i.uuid;let c=this.cache.get(l);c||(c=new xt.ObjectConstructors.PointsMaterial,tn.prototype.copy.call(c,i),c.color.copy(i.color),c.map=i.map,c.sizeAttenuation=!1,this.cache.add(l,c)),i=c}else if(e.isLine){const l="LineBasicMaterial:"+i.uuid;let c=this.cache.get(l);c||(c=new xt.ObjectConstructors.LineBasicMaterial,tn.prototype.copy.call(c,i),c.color.copy(i.color),c.map=i.map,this.cache.add(l,c)),i=c}const o=i.userData&&i.userData.gltfExtensions?!!i.userData.gltfExtensions.WEBGI_material_extras:!1;if((n||s||a)&&!o){let l="ClonedMaterial:"+i.uuid+":";n&&(l+="derivative-tangents:"),s&&(l+="vertex-colors:"),a&&(l+="flat-shading:");let c=this.cache.get(l);c||(c=i.clone(),s&&(c.vertexColors=!0),a&&(c.flatShading=!0),n&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(l,c),this.associations.set(c,this.associations.get(i))),i=c}e.material=i}getMaterialType(){return xt.ObjectConstructors.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,n=this.extensions,s=i.materials[e];let a;const o={},l=s.extensions||{},c=[];if(l[Ht.KHR_MATERIALS_UNLIT]){const u=n[Ht.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),c.push(u.extendParams(o,s,t))}else{const u=s.pbrMetallicRoughness||{};if(o.color=new se(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){const d=u.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],Dt),o.opacity=d[3]}u.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",u.baseColorTexture,vt)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=Zi);const h=s.alphaMode||S0.OPAQUE;if(h===S0.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===S0.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==xt.ObjectConstructors.MeshBasicMaterial&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new $(1,1),s.normalTexture.scale!==void 0)){const u=s.normalTexture.scale;o.normalScale.set(u,u)}if(s.occlusionTexture!==void 0&&a!==xt.ObjectConstructors.MeshBasicMaterial&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==xt.ObjectConstructors.MeshBasicMaterial){const u=s.emissiveFactor;o.emissive=new se().setRGB(u[0],u[1],u[2],Dt)}return s.emissiveTexture!==void 0&&a!==xt.ObjectConstructors.MeshBasicMaterial&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,vt)),Promise.all(c).then(function(){const u=new a(o);return s.extras&&s.extras.uuid&&(u.uuid=s.extras.uuid),s.name&&(u.name=s.name),kr(u,s),t.associations.set(u,{materials:e}),s.extensions&&xa(n,u,s),u})}createUniqueName(e){const t=Ct.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,n=this.primitiveCache;function s(o){return i[Ht.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return uT(l,o,t)})}const a=[];for(let o=0,l=e.length;o<l;o++){const c=e[o],h=OG(c),u=n[h];if(u)a.push(u.promise);else{let d;c.extensions&&c.extensions[Ht.KHR_DRACO_MESH_COMPRESSION]?d=s(c):d=uT(new $e,c,t),n[h]={primitive:c,promise:d},a.push(d)}}return Promise.all(a)}loadMesh(e){const t=this,i=this.json,n=this.extensions,s=i.meshes[e],a=s.primitives,o=[];for(let l=0,c=a.length;l<c;l++){const h=a[l].material===void 0?RG(this.cache):this.getDependency("material",a[l].material);o.push(h)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){const c=l.slice(0,l.length-1),h=l[l.length-1],u=[];for(let p=0,m=h.length;p<m;p++){const A=h[p],g=a[p];let y;const _=c[p];if(g.mode===Ws.TRIANGLES||g.mode===Ws.TRIANGLE_STRIP||g.mode===Ws.TRIANGLE_FAN||g.mode===void 0)y=s.isSkinnedMesh===!0?new np(A,_):new ye(A,_),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),g.mode===Ws.TRIANGLE_STRIP?y.geometry=wv(y.geometry,hw):g.mode===Ws.TRIANGLE_FAN&&(y.geometry=wv(y.geometry,CA));else if(g.mode===Ws.LINES)y=new Is(A,_);else if(g.mode===Ws.LINE_STRIP)y=new fn(A,_);else if(g.mode===Ws.LINE_LOOP)y=new dy(A,_);else if(g.mode===Ws.POINTS)y=new jo(A,_);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(y.geometry.morphAttributes).length>0&&LG(y,s),y.name=t.createUniqueName(s.name||"mesh_"+e),y.geometry&&s.extras&&s.extras.isGeometryUserData?(kr(y.geometry,s),g.extensions&&xa(n,y.geometry,g)):(kr(y,s),g.extensions&&xa(n,y,g)),t.assignFinalMaterial(y),u.push(y)}s.extensions&&u.forEach(p=>xa(n,p,s));for(let p=0,m=u.length;p<m;p++)t.associations.set(u[p],{meshes:e,primitives:p});if(u.length===1)return s.extensions&&xa(n,u[0],s),u[0];const d=new Ri;s.extensions&&xa(n,d,s),t.associations.set(d,{meshes:e});for(let p=0,m=u.length;p<m;p++)d.add(u[p]);return d})}loadCamera(e){let t;const i=this.json.cameras[e],n=i[i.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new xt.ObjectConstructors.PerspectiveCamera(Ut.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):i.type==="orthographic"&&(t=new xt.ObjectConstructors.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),kr(t,i),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],i=[];for(let n=0,s=t.joints.length;n<s;n++)i.push(this._loadNodeShallow(t.joints[n]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(n){const s=n.pop(),a=n,o=[],l=[];for(let c=0,h=a.length;c<h;c++){const u=a[c];if(u){o.push(u);const d=new pe;s!==null&&d.fromArray(s.array,c*16),l.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new Dc(o,l)})}loadAnimation(e){const t=this.json,i=this,n=t.animations[e],s=n.name?n.name:"animation_"+e,a=[],o=[],l=[],c=[],h=[];for(let u=0,d=n.channels.length;u<d;u++){const p=n.channels[u],m=n.samplers[p.sampler],A=p.target,g=A.node,y=n.parameters!==void 0?n.parameters[m.input]:m.input,_=n.parameters!==void 0?n.parameters[m.output]:m.output;A.node!==void 0&&(a.push(this.getDependency("node",g)),o.push(this.getDependency("accessor",y)),l.push(this.getDependency("accessor",_)),c.push(m),h.push(A))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(h)]).then(function(u){const d=u[0],p=u[1],m=u[2],A=u[3],g=u[4],y=[];for(let v=0,b=d.length;v<b;v++){const T=d[v],E=p[v],M=m[v],S=A[v],w=g[v];if(T===void 0)continue;T.updateMatrix&&T.updateMatrix();const C=i._createAnimationTracks(T,E,M,S,w);if(C)for(let D=0;D<C.length;D++)y.push(C[D])}const _=new eo(s,void 0,y);return kr(_,n),_})}createNodeMesh(e){const t=this.json,i=this,n=t.nodes[e];return n.mesh===void 0?null:i.getDependency("mesh",n.mesh).then(function(s){const a=i._getNodeRef(i.meshCache,n.mesh,s);return n.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=n.weights.length;l<c;l++)o.morphTargetInfluences[l]=n.weights[l]}),a})}loadNode(e){const t=this.json,i=this,n=t.nodes[e],s=i._loadNodeShallow(e),a=[],o=n.children||[];for(let c=0,h=o.length;c<h;c++)a.push(i.getDependency("node",o[c]));const l=n.skin===void 0?Promise.resolve(null):i.getDependency("skin",n.skin);return Promise.all([s,Promise.all(a),l]).then(function(c){const h=c[0],u=c[1],d=c[2];d!==null&&h.traverse(function(p){p.isSkinnedMesh&&p.bind(d,FG)});for(let p=0,m=u.length;p<m;p++)h.add(u[p]);return h})}_loadNodeShallow(e){const t=this.json,i=this.extensions,n=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],a=s.name?n.createUniqueName(s.name):"",o=[],l=n._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(n.getDependency("camera",s.camera).then(function(c){return n._getNodeRef(n.cameraCache,s.camera,c)})),n._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let h;if(s.isBone===!0?h=new Pc:c.length>1?h=new Ri:c.length===1?h=c[0]:h=new ft,h!==c[0])for(let u=0,d=c.length;u<d;u++)h.add(c[u]);if(s.name&&(h.userData.name=s.name,h.name=a),kr(h,s),s.extensions&&xa(i,h,s),s.matrix!==void 0){const u=new pe;u.fromArray(s.matrix),h.applyMatrix4(u)}else s.translation!==void 0&&h.position.fromArray(s.translation),s.rotation!==void 0&&h.quaternion.fromArray(s.rotation),s.scale!==void 0&&h.scale.fromArray(s.scale);return n.associations.has(h)||n.associations.set(h,{}),n.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],n=this,s=new Ri;i.name&&(s.name=n.createUniqueName(i.name)),kr(s,i),i.extensions&&xa(t,s,i);const a=i.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(n.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let h=0,u=l.length;h<u;h++)s.add(l[h]);const c=h=>{const u=new Map;for(const[d,p]of n.associations)(d instanceof tn||d instanceof Rt)&&u.set(d,p);return h.traverse(d=>{const p=n.associations.get(d);p!=null&&u.set(d,p)}),u};return n.associations=c(s),s})}_createAnimationTracks(e,t,i,n,s){const a=[],o=e.name?e.name:e.uuid,l=[];po[s.path]===po.weights?e.traverse(function(d){d.morphTargetInfluences&&l.push(d.name?d.name:d.uuid)}):l.push(o);let c;switch(po[s.path]){case po.weights:c=Ja;break;case po.rotation:c=Ir;break;case po.position:case po.scale:c=Za;break;default:switch(i.itemSize){case 1:c=Ja;break;case 2:case 3:default:c=Za;break}break}const h=n.interpolation!==void 0?DG[n.interpolation]:Ro,u=this._getArrayFromAccessor(i);for(let d=0,p=l.length;d<p;d++){const m=new c(l[d]+"."+po[s.path],t.array,u,h);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(m),a.push(m)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const i=M0(t.constructor),n=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s++)n[s]=t[s]*i;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){const n=this instanceof Ir?PG:oT;return new n(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function NG(r,e,t){const i=e.attributes,n=new en;if(i.POSITION!==void 0){const o=t.json.accessors[i.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(n.set(new x(l[0],l[1],l[2]),new x(c[0],c[1],c[2])),o.normalized){const h=M0(ah[o.componentType]);n.min.multiplyScalar(h),n.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const o=new x,l=new x;for(let c=0,h=s.length;c<h;c++){const u=s[c];if(u.POSITION!==void 0){const d=t.json.accessors[u.POSITION],p=d.min,m=d.max;if(p!==void 0&&m!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(m[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(m[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(m[2]))),d.normalized){const A=M0(ah[d.componentType]);l.multiplyScalar(A)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(o)}r.boundingBox=n;const a=new un;n.getCenter(a.center),a.radius=n.min.distanceTo(n.max)/2,r.boundingSphere=a}function uT(r,e,t){const i=e.attributes,n=[];function s(a,o){return t.getDependency("accessor",a).then(function(l){r.setAttribute(o,l)})}for(const a in i){const o=x0[a]||a.toLowerCase();o in r.attributes||n.push(s(i[a],o))}if(e.indices!==void 0&&!r.index){const a=t.getDependency("accessor",e.indices).then(function(o){r.setIndex(o)});n.push(a)}return Xt.workingColorSpace!==Dt&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Xt.workingColorSpace}" not supported.`),kr(r,e),NG(r,e,t),Promise.all(n).then(function(){return e.targets!==void 0?BG(r,e.targets,t):r})}const dT=async(r,e)=>{if(!r||!(r instanceof ArrayBuffer)||!r.byteLength||!e.encrypt)return r;if(!e.encryptKey&&window&&window.prompt&&(e.encryptKey=window.prompt("GLTFEncryption: Enter encryption key/password")||""),!e.encryptKey)return console.warn("GLTF Export: encryption key not provided, skipping encryption"),r;const t=await iS(new Uint8Array(r),e.encryptKey);return bE(t,{asset:{version:"2.0",generator:"ThreePipeGLBWrapper",encryption:{type:"aesgcm",version:1}}})},fT={key:(r,e,t)=>r.key||window&&window.prompt&&window.prompt("GLTFEncryption: Please enter the password/key for the model: "+t)||"",async process(r,e){if(typeof r=="string"||r.byteLength<100)return r;const t=100;if(!new TextDecoder().decode(new Uint8Array(r,0,t)).includes("GLBWrapper"))return r;const n=new w0(r),s=JSON.parse(n.content||"{}");let a=n.body||r;const o=s.asset?.encryption;if(!o)return a;const l=o.type,c=o.version;if(l==="aesgcm"&&c===1){const h=await it(this.key,o,s,e)||"";try{a=(await nS(new Uint8Array(a),h)).buffer}catch{throw new ErrorEvent("decryption error")}}return a}},jg=class jg extends Zt{async parseAsync(e){return e}load(e,t,i,n){return super.load(e,s=>{try{if(typeof s=="string")this.parseAsync(JSON.parse(s)).then(t);else throw new Error("Invalid JSON")}catch(a){n?.(a)}},i,n)}};jg.SupportedJSONTypes=[],jg.SupportedJSONExtensions=[];let Pd=jg;const Nl=class Nl extends Pd{async parseAsync(e){if(!this.viewer)throw"Viewer not set in JSONMaterialLoader.";let t;return Nl.FindExistingMaterial&&e.uuid&&this.viewer&&(t=this.viewer.materialManager.findMaterial(e.uuid)),await Nl.DeserializeMaterialJSON(e,this.viewer,void 0,t)}static async DeserializeMaterialJSON(e,t,i,n){i=i||Fr();const s={...e};e.images&&(Array.isArray(e.images)?i.images=Object.fromEntries(e.images.map(o=>[o.uuid,o])):i.images=e.images,delete s.images),e.textures&&(Array.isArray(e.textures)?i.textures=Object.fromEntries(e.textures.map(o=>[o.uuid,o])):i.textures=e.textures,delete s.textures),e.materials&&(Array.isArray(e.materials)?i.materials=Object.fromEntries(e.materials.map(o=>[o.uuid,o])):i.materials=e.materials,delete s.materials);const a=await t.loadConfigResources(i);return ke.Deserialize(s,n||void 0,a)}};Nl.SupportedJSONTypes=()=>["Material",...[...ke.SerializableMaterials.values()].flatMap(e=>[e.TYPE,...e.TypeAlias||[]])],Nl.SupportedJSONExtensions=()=>["mat",...[...ke.SerializableMaterials.values()].map(e=>e.TypeSlug)],Nl.FindExistingMaterial=!1;let oh=Nl;class T0 extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=this.path===""?Rs.extractUrlBase(e):this.path,o=new Zt(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){n?n(c):console.error(c),s.manager.itemError(e)}},i,n)}setMaterialOptions(e){return this.materialOptions=e,this}parse(e,t){const i=e.split(`
`);let n={};const s=/\s+/,a={};for(let l=0;l<i.length;l++){let c=i[l];if(c=c.trim(),c.length===0||c.charAt(0)==="#")continue;const h=c.indexOf(" ");let u=h>=0?c.substring(0,h):c;u=u.toLowerCase();let d=h>=0?c.substring(h+1):"";if(d=d.trim(),u==="newmtl")n={name:d},a[d]=n;else if(u==="ka"||u==="kd"||u==="ks"||u==="ke"){const p=d.split(s,3);n[u]=[parseFloat(p[0]),parseFloat(p[1]),parseFloat(p[2])]}else n[u]=d}const o=new kG(this.resourcePath||t,this.materialOptions);return o.setCrossOrigin(this.crossOrigin),o.setManager(this.manager),o.setMaterials(a),o}}class kG{constructor(e="",t={}){this.baseUrl=e,this.options=t,this.materialsInfo={},this.materials={},this.materialsArray=[],this.nameLookup={},this.crossOrigin="anonymous",this.side=this.options.side!==void 0?this.options.side:fs,this.wrap=this.options.wrap!==void 0?this.options.wrap:Bn}setCrossOrigin(e){return this.crossOrigin=e,this}setManager(e){this.manager=e}setMaterials(e){this.materialsInfo=this.convert(e),this.materials={},this.materialsArray=[],this.nameLookup={}}convert(e){if(!this.options)return e;const t={};for(const i in e){const n=e[i],s={};t[i]=s;for(const a in n){let o=!0,l=n[a];const c=a.toLowerCase();switch(c){case"kd":case"ka":case"ks":this.options&&this.options.normalizeRGB&&(l=[l[0]/255,l[1]/255,l[2]/255]),this.options&&this.options.ignoreZeroRGBs&&l[0]===0&&l[1]===0&&l[2]===0&&(o=!1);break}o&&(s[c]=l)}}return t}async preload(){for(const e in this.materialsInfo)await this.create(e)}getIndex(e){return this.nameLookup[e]}async getAsArray(){let e=0;for(const t in this.materialsInfo)this.materialsArray[e]=await this.create(t),this.nameLookup[t]=e,e++;return this.materialsArray}async create(e){return this.materials[e]===void 0&&await this.createMaterial_(e),this.materials[e]}async createMaterial_(e){const t=this,i=this.materialsInfo[e],n={name:e,side:this.side};function s(c,h){return typeof h!="string"||h===""?"":/^https?:\/\//i.test(h)?h:c+h}async function a(c,h){if(n[c])return;const u=t.getTextureParams(h,n);return new Promise((d,p)=>{let m=!1,A=()=>!m&&(m=!0)&&d();const g=t.loadTexture(s(t.baseUrl,u.url),void 0,y=>{n[c]=y,A()},void 0,A);setTimeout(A,50),g.repeat.copy(u.scale),g.offset.copy(u.offset),g.wrapS=t.wrap,g.wrapT=t.wrap,(c==="map"||c==="emissiveMap")&&(g.colorSpace=vt)})}const o=Array.from(Object.keys(i||{}));let l=o.includes("d")||o.includes("D");for(const c of o){const h=i[c];let u;if(h!=="")switch(c.toLowerCase()){case"kd":n.color=new se().fromArray(h).convertSRGBToLinear();break;case"ks":n.specular=new se().fromArray(h).convertSRGBToLinear();break;case"ke":n.emissive=new se().fromArray(h).convertSRGBToLinear();break;case"map_kd":await a("map",h);break;case"map_ks":await a("specularMap",h);break;case"map_ke":await a("emissiveMap",h);break;case"norm":await a("normalMap",h);break;case"map_bump":case"bump":await a("bumpMap",h);break;case"map_d":await a("alphaMap",h),n.transparent=!0;break;case"ns":n.shininess=parseFloat(h);break;case"d":u=parseFloat(h),u<1&&(n.opacity=u,n.transparent=!0);break;case"tr":if(l)break;u=parseFloat(h),this.options&&this.options.invertTrProperty&&(u=1-u),u>0&&(n.opacity=1-u,n.transparent=!0);break}}return this.materials[e]=new Ko(n),this.materials[e]}getTextureParams(e,t){const i={scale:new $(1,1),offset:new $(0,0)},n=e.split(/\s+/);let s;return s=n.indexOf("-bm"),s>=0&&(t.bumpScale=parseFloat(n[s+1]),n.splice(s,2)),s=n.indexOf("-s"),s>=0&&(i.scale.set(parseFloat(n[s+1]),parseFloat(n[s+2])),n.splice(s,4)),s=n.indexOf("-o"),s>=0&&(i.offset.set(parseFloat(n[s+1]),parseFloat(n[s+2])),n.splice(s,4)),i.url=n.join(" ").trim(),i}loadTexture(e,t,i,n,s){const a=this.manager!==void 0?this.manager:Ty;let o=a.getHandler(e);o===null&&(o=new to(a)),o.setCrossOrigin&&o.setCrossOrigin(this.crossOrigin);const l=o.load(e,i,n,s);return t!==void 0&&(l.mapping=t),l}}const GG=/^[og]\s*(.+)?/,zG=/^mtllib /,VG=/^usemtl /,HG=/^usemap /,pT=/\s+/,mT=new x,I0=new x,gT=new x,AT=new x,qs=new x,$m=new se;function QG(){const r={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(n,s){const a=this._finalize(!1);a&&(a.inherited||a.groupCount<=0)&&this.materials.splice(a.index,1);const o={index:this.materials.length,name:n||"",mtllib:Array.isArray(s)&&s.length>0?s[s.length-1]:"",smooth:a!==void 0?a.smooth:this.smooth,groupStart:a!==void 0?a.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(n){const s=this.currentMaterial();if(s&&s.groupEnd===-1&&(s.groupEnd=this.geometry.vertices.length/3,s.groupCount=s.groupEnd-s.groupStart,s.inherited=!1),n&&this.materials.length>1)for(let a=this.materials.length-1;a>=0;a--)this.materials[a].groupCount<=0&&this.materials.splice(a,1);return n&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),s}},i&&i.name&&typeof i.clone=="function"){const n=i.clone(0);n.inherited=!0,this.object.materials.push(n)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const n=this.vertices,s=this.object.geometry.vertices;s.push(n[e+0],n[e+1],n[e+2]),s.push(n[t+0],n[t+1],n[t+2]),s.push(n[i+0],n[i+1],n[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const n=this.normals,s=this.object.geometry.normals;s.push(n[e+0],n[e+1],n[e+2]),s.push(n[t+0],n[t+1],n[t+2]),s.push(n[i+0],n[i+1],n[i+2])},addFaceNormal:function(e,t,i){const n=this.vertices,s=this.object.geometry.normals;mT.fromArray(n,e),I0.fromArray(n,t),gT.fromArray(n,i),qs.subVectors(gT,I0),AT.subVectors(mT,I0),qs.cross(AT),qs.normalize(),s.push(qs.x,qs.y,qs.z),s.push(qs.x,qs.y,qs.z),s.push(qs.x,qs.y,qs.z)},addColor:function(e,t,i){const n=this.colors,s=this.object.geometry.colors;n[e]!==void 0&&s.push(n[e+0],n[e+1],n[e+2]),n[t]!==void 0&&s.push(n[t+0],n[t+1],n[t+2]),n[i]!==void 0&&s.push(n[i+0],n[i+1],n[i+2])},addUV:function(e,t,i){const n=this.uvs,s=this.object.geometry.uvs;s.push(n[e+0],n[e+1]),s.push(n[t+0],n[t+1]),s.push(n[i+0],n[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,n,s,a,o,l,c){const h=this.vertices.length;let u=this.parseVertexIndex(e,h),d=this.parseVertexIndex(t,h),p=this.parseVertexIndex(i,h);if(this.addVertex(u,d,p),this.addColor(u,d,p),o!==void 0&&o!==""){const m=this.normals.length;u=this.parseNormalIndex(o,m),d=this.parseNormalIndex(l,m),p=this.parseNormalIndex(c,m),this.addNormal(u,d,p)}else this.addFaceNormal(u,d,p);if(n!==void 0&&n!==""){const m=this.uvs.length;u=this.parseUVIndex(n,m),d=this.parseUVIndex(s,m),p=this.parseUVIndex(a,m),this.addUV(u,d,p),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,n=e.length;i<n;i++){const s=this.parseVertexIndex(e[i],t);this.addVertexPoint(s),this.addColor(s)}},addLineGeometry:function(e,t){this.object.geometry.type="Line";const i=this.vertices.length,n=this.uvs.length;for(let s=0,a=e.length;s<a;s++)this.addVertexLine(this.parseVertexIndex(e[s],i));for(let s=0,a=t.length;s<a;s++)this.addUVLine(this.parseUVIndex(t[s],n))}};return r.startObject("",!1),r}class yT extends li{constructor(e){super(e),this.materials=null}load(e,t,i,n){const s=this,a=new Zt(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),s.currentUrl=e,a.load(e,async function(o){try{t(await s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}s.currentUrl=void 0},i,n)}setMaterials(e){return this.materials=e,this}async parse(e){const t=new QG;e.indexOf(`\r
`)!==-1&&(e=e.replace(/\r\n/g,`
`)),e.indexOf(`\\
`)!==-1&&(e=e.replace(/\\\n/g,""));const i=e.split(`
`);let n=[];for(let o=0,l=i.length;o<l;o++){const c=i[o].trimStart();if(c.length===0)continue;const h=c.charAt(0);if(h!=="#")if(h==="v"){const u=c.split(pT);switch(u[0]){case"v":t.vertices.push(parseFloat(u[1]),parseFloat(u[2]),parseFloat(u[3])),u.length>=7?($m.setRGB(parseFloat(u[4]),parseFloat(u[5]),parseFloat(u[6])).convertSRGBToLinear(),t.colors.push($m.r,$m.g,$m.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(u[1]),parseFloat(u[2]),parseFloat(u[3]));break;case"vt":t.uvs.push(parseFloat(u[1]),parseFloat(u[2]));break}}else if(h==="f"){const d=c.slice(1).trim().split(pT),p=[];for(let A=0,g=d.length;A<g;A++){const y=d[A];if(y.length>0){const _=y.split("/");p.push(_)}}const m=p[0];for(let A=1,g=p.length-1;A<g;A++){const y=p[A],_=p[A+1];t.addFace(m[0],y[0],_[0],m[1],y[1],_[1],m[2],y[2],_[2])}}else if(h==="l"){const u=c.substring(1).trim().split(" ");let d=[];const p=[];if(c.indexOf("/")===-1)d=u;else for(let m=0,A=u.length;m<A;m++){const g=u[m].split("/");g[0]!==""&&d.push(g[0]),g[1]!==""&&p.push(g[1])}t.addLineGeometry(d,p)}else if(h==="p"){const d=c.slice(1).trim().split(" ");t.addPointGeometry(d)}else if((n=GG.exec(c))!==null){const u=(" "+n[0].slice(1).trim()).slice(1);t.startObject(u)}else if(VG.test(c))t.object.startMaterial(c.substring(7).trim(),t.materialLibraries);else if(zG.test(c)){t.materialLibraries.push(c.substring(7).trim());let u=c.substring(7).trim(),d=this.manager.getHandler(u);if(!d&&u.trim().split("?")[0].endsWith(".mtl")&&(d=new T0(this.manager),d.setPath(this.path),d.setWithCredentials(this.withCredentials),d.setRequestHeader(this.requestHeader),d.setResourcePath(this.resourcePath),d.setCrossOrigin(this.crossOrigin)),this.currentUrl.startsWith("http")&&!u.startsWith("http")&&(u=this.currentUrl.substring(0,this.currentUrl.lastIndexOf("/")+1)+u),!d)console.warn("OBJLoader2: Register MTLLoader2 or any other material loader to loading manager to load the material file:",u);else{const p=await d.loadAsync(u).catch(m=>{console.warn(m)});p&&this.setMaterials(p)}}else if(HG.test(c))console.warn('OBJLoader2: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(h==="s"){if(n=c.split(" "),n.length>1){const d=n[1].trim().toLowerCase();t.object.smooth=d!=="0"&&d!=="off"}else t.object.smooth=!0;const u=t.object.currentMaterial();u&&(u.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const s=new Ri;if(s.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o<l;o++){const c=t.objects[o],h=c.geometry,u=c.materials,d=h.type==="Line",p=h.type==="Points";let m=!1;if(h.vertices.length===0)continue;const A=new $e;A.setAttribute("position",new Me(h.vertices,3)),h.normals.length>0&&A.setAttribute("normal",new Me(h.normals,3)),h.colors.length>0&&(m=!0,A.setAttribute("color",new Me(h.colors,3))),h.hasUVIndices===!0&&A.setAttribute("uv",new Me(h.uvs,2));const g=[];for(let _=0,v=u.length;_<v;_++){const b=u[_],T=b.name+"_"+b.smooth+"_"+m;let E=t.materials[T];if(this.materials!==null){if(E=await this.materials.create(b.name),d&&E&&!(E instanceof Ei)){const M=new Ei;tn.prototype.copy.call(M,E),M.color.copy(E.color),E=M}else if(p&&E&&!(E instanceof Tr)){const M=new Tr({size:10,sizeAttenuation:!1});tn.prototype.copy.call(M,E),M.color.copy(E.color),M.map=E.map,E=M}}E===void 0&&(d?E=new Ei:p?E=new Tr({size:1,sizeAttenuation:!1}):E=new Ka,E.name=b.name,E.flatShading=!b.smooth,E.vertexColors=m,t.materials[T]=E),g.push(E)}let y;if(g.length>1){for(let _=0,v=u.length;_<v;_++){const b=u[_];A.addGroup(b.groupStart,b.groupCount,_)}d?y=new Is(A,g):p?y=new jo(A,g):y=new ye(A,g)}else d?y=new Is(A,g[0]):p?y=new jo(A,g[0]):y=new ye(A,g[0]);y.name=c.name,s.add(y)}else if(t.vertices.length>0){const o=new Tr({size:1,sizeAttenuation:!1}),l=new $e;l.setAttribute("position",new Me(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Me(t.colors,3)),o.vertexColors=!0);const c=new jo(l,o);s.add(c)}return s}}/*!
fflate - fast JavaScript compression/decompression
<https://101arrowz.github.io/fflate>
Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
version 0.8.2
*/var vT={},jG=(function(r,e,t,i,n){var s=new Worker(vT[e]||(vT[e]=URL.createObjectURL(new Blob([r+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return s.onmessage=function(a){var o=a.data,l=o.$e$;if(l){var c=new Error(l[0]);c.code=l[1],c.stack=l[2],n(c,null)}else n(null,o)},s.postMessage(t,i),s}),St=Uint8Array,os=Uint16Array,Dd=Int32Array,lh=new St([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ch=new St([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Rd=new St([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_T=function(r,e){for(var t=new os(31),i=0;i<31;++i)t[i]=e+=1<<r[i-1];for(var n=new Dd(t[30]),i=1;i<30;++i)for(var s=t[i];s<t[i+1];++s)n[s]=s-t[i]<<5|i;return{b:t,r:n}},bT=_T(lh,2),P0=bT.b,Km=bT.r;P0[28]=258,Km[258]=28;for(var wT=_T(ch,0),CT=wT.b,D0=wT.r,Bd=new os(32768),xi=0;xi<32768;++xi){var mo=(xi&43690)>>1|(xi&21845)<<1;mo=(mo&52428)>>2|(mo&13107)<<2,mo=(mo&61680)>>4|(mo&3855)<<4,Bd[xi]=((mo&65280)>>8|(mo&255)<<8)>>1}for(var Xs=(function(r,e,t){for(var i=r.length,n=0,s=new os(e);n<i;++n)r[n]&&++s[r[n]-1];var a=new os(e);for(n=1;n<e;++n)a[n]=a[n-1]+s[n-1]<<1;var o;if(t){o=new os(1<<e);var l=15-e;for(n=0;n<i;++n)if(r[n])for(var c=n<<4|r[n],h=e-r[n],u=a[r[n]-1]++<<h,d=u|(1<<h)-1;u<=d;++u)o[Bd[u]>>l]=c}else for(o=new os(i),n=0;n<i;++n)r[n]&&(o[n]=Bd[a[r[n]-1]++]>>15-r[n]);return o}),Sa=new St(288),xi=0;xi<144;++xi)Sa[xi]=8;for(var xi=144;xi<256;++xi)Sa[xi]=9;for(var xi=256;xi<280;++xi)Sa[xi]=7;for(var xi=280;xi<288;++xi)Sa[xi]=8;for(var hh=new St(32),xi=0;xi<32;++xi)hh[xi]=5;var xT=Xs(Sa,9,0),ST=Xs(Sa,9,1),ET=Xs(hh,5,0),MT=Xs(hh,5,1),Jm=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},Ys=function(r,e,t){var i=e/8|0;return(r[i]|r[i+1]<<8)>>(e&7)&t},Zm=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},uh=function(r){return(r+7)/8|0},$s=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new St(r.subarray(e,t))},WG={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14},TT=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Je=function(r,e,t){var i=new Error(e||TT[r]);if(i.code=r,Error.captureStackTrace&&Error.captureStackTrace(i,Je),!t)throw i;return i},Ld=function(r,e,t,i){var n=r.length,s=i?i.length:0;if(!n||e.f&&!e.l)return t||new St(0);var a=!t,o=a||e.i!=2,l=e.i;a&&(t=new St(n*3));var c=function(Y){var fe=t.length;if(Y>fe){var he=new St(Math.max(fe*2,Y));he.set(t),t=he}},h=e.f||0,u=e.p||0,d=e.b||0,p=e.l,m=e.d,A=e.m,g=e.n,y=n*8;do{if(!p){h=Ys(r,u,1);var _=Ys(r,u+1,3);if(u+=3,_)if(_==1)p=ST,m=MT,A=9,g=5;else if(_==2){var E=Ys(r,u,31)+257,M=Ys(r,u+10,15)+4,S=E+Ys(r,u+5,31)+1;u+=14;for(var w=new St(S),C=new St(19),D=0;D<M;++D)C[Rd[D]]=Ys(r,u+D*3,7);u+=M*3;for(var O=Jm(C),F=(1<<O)-1,G=Xs(C,O,1),D=0;D<S;){var j=G[Ys(r,u,F)];u+=j&15;var v=j>>4;if(v<16)w[D++]=v;else{var W=0,K=0;for(v==16?(K=3+Ys(r,u,3),u+=2,W=w[D-1]):v==17?(K=3+Ys(r,u,7),u+=3):v==18&&(K=11+Ys(r,u,127),u+=7);K--;)w[D++]=W}}var q=w.subarray(0,E),oe=w.subarray(E);A=Jm(q),g=Jm(oe),p=Xs(q,A,1),m=Xs(oe,g,1)}else Je(1);else{var v=uh(u)+4,b=r[v-4]|r[v-3]<<8,T=v+b;if(T>n){l&&Je(0);break}o&&c(d+b),t.set(r.subarray(v,T),d),e.b=d+=b,e.p=u=T*8,e.f=h;continue}if(u>y){l&&Je(0);break}}o&&c(d+131072);for(var re=(1<<A)-1,Ce=(1<<g)-1,Ie=u;;Ie=u){var W=p[Zm(r,u)&re],Ue=W>>4;if(u+=W&15,u>y){l&&Je(0);break}if(W||Je(2),Ue<256)t[d++]=Ue;else if(Ue==256){Ie=u,p=null;break}else{var te=Ue-254;if(Ue>264){var D=Ue-257,ce=lh[D];te=Ys(r,u,(1<<ce)-1)+P0[D],u+=ce}var me=m[Zm(r,u)&Ce],we=me>>4;me||Je(3),u+=me&15;var oe=CT[we];if(we>3){var ce=ch[we];oe+=Zm(r,u)&(1<<ce)-1,u+=ce}if(u>y){l&&Je(0);break}o&&c(d+131072);var je=d+te;if(d<oe){var ht=s-oe,Ze=Math.min(oe,je);for(ht+d<0&&Je(3);d<Ze;++d)t[d]=i[ht+d]}for(;d<je;++d)t[d]=t[d-oe]}}e.l=p,e.p=Ie,e.b=d,e.f=h,p&&(h=1,e.m=A,e.d=m,e.n=g)}while(!h);return d!=t.length&&a?$s(t,0,d):t.subarray(0,d)},Gr=function(r,e,t){t<<=e&7;var i=e/8|0;r[i]|=t,r[i+1]|=t>>8},dh=function(r,e,t){t<<=e&7;var i=e/8|0;r[i]|=t,r[i+1]|=t>>8,r[i+2]|=t>>16},eg=function(r,e){for(var t=[],i=0;i<r.length;++i)r[i]&&t.push({s:i,f:r[i]});var n=t.length,s=t.slice();if(!n)return{t:go,l:0};if(n==1){var a=new St(t[0].s+1);return a[t[0].s]=1,{t:a,l:1}}t.sort(function(T,E){return T.f-E.f}),t.push({s:-1,f:25001});var o=t[0],l=t[1],c=0,h=1,u=2;for(t[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=n-1;)o=t[t[c].f<t[u].f?c++:u++],l=t[c!=h&&t[c].f<t[u].f?c++:u++],t[h++]={s:-1,f:o.f+l.f,l:o,r:l};for(var d=s[0].s,i=1;i<n;++i)s[i].s>d&&(d=s[i].s);var p=new os(d+1),m=tg(t[h-1],p,0);if(m>e){var i=0,A=0,g=m-e,y=1<<g;for(s.sort(function(E,M){return p[M.s]-p[E.s]||E.f-M.f});i<n;++i){var _=s[i].s;if(p[_]>e)A+=y-(1<<m-p[_]),p[_]=e;else break}for(A>>=g;A>0;){var v=s[i].s;p[v]<e?A-=1<<e-p[v]++-1:++i}for(;i>=0&&A;--i){var b=s[i].s;p[b]==e&&(--p[b],++A)}m=e}return{t:new St(p),l:m}},tg=function(r,e,t){return r.s==-1?Math.max(tg(r.l,e,t+1),tg(r.r,e,t+1)):e[r.s]=t},R0=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new os(++e),i=0,n=r[0],s=1,a=function(l){t[i++]=l},o=1;o<=e;++o)if(r[o]==n&&o!=e)++s;else{if(!n&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(n),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(n);s=1,n=r[o]}return{c:t.subarray(0,i),n:e}},fh=function(r,e){for(var t=0,i=0;i<e.length;++i)t+=r[i]*e[i];return t},B0=function(r,e,t){var i=t.length,n=uh(e+2);r[n]=i&255,r[n+1]=i>>8,r[n+2]=r[n]^255,r[n+3]=r[n+1]^255;for(var s=0;s<i;++s)r[n+s+4]=t[s];return(n+4+i)*8},L0=function(r,e,t,i,n,s,a,o,l,c,h){Gr(e,h++,t),++n[256];for(var u=eg(n,15),d=u.t,p=u.l,m=eg(s,15),A=m.t,g=m.l,y=R0(d),_=y.c,v=y.n,b=R0(A),T=b.c,E=b.n,M=new os(19),S=0;S<_.length;++S)++M[_[S]&31];for(var S=0;S<T.length;++S)++M[T[S]&31];for(var w=eg(M,7),C=w.t,D=w.l,O=19;O>4&&!C[Rd[O-1]];--O);var F=c+5<<3,G=fh(n,Sa)+fh(s,hh)+a,j=fh(n,d)+fh(s,A)+a+14+3*O+fh(M,C)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&F<=G&&F<=j)return B0(e,h,r.subarray(l,l+c));var W,K,q,oe;if(Gr(e,h,1+(j<G)),h+=2,j<G){W=Xs(d,p,0),K=d,q=Xs(A,g,0),oe=A;var re=Xs(C,D,0);Gr(e,h,v-257),Gr(e,h+5,E-1),Gr(e,h+10,O-4),h+=14;for(var S=0;S<O;++S)Gr(e,h+3*S,C[Rd[S]]);h+=3*O;for(var Ce=[_,T],Ie=0;Ie<2;++Ie)for(var Ue=Ce[Ie],S=0;S<Ue.length;++S){var te=Ue[S]&31;Gr(e,h,re[te]),h+=C[te],te>15&&(Gr(e,h,Ue[S]>>5&127),h+=Ue[S]>>12)}}else W=xT,K=Sa,q=ET,oe=hh;for(var S=0;S<o;++S){var ce=i[S];if(ce>255){var te=ce>>18&31;dh(e,h,W[te+257]),h+=K[te+257],te>7&&(Gr(e,h,ce>>23&31),h+=lh[te]);var me=ce&31;dh(e,h,q[me]),h+=oe[me],me>3&&(dh(e,h,ce>>5&8191),h+=ch[me])}else dh(e,h,W[ce]),h+=K[ce]}return dh(e,h,W[256]),h+K[256]},IT=new Dd([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),go=new St(0),PT=function(r,e,t,i,n,s){var a=s.z||r.length,o=new St(i+a+5*(1+Math.ceil(a/7e3))+n),l=o.subarray(i,o.length-n),c=s.l,h=(s.r||0)&7;if(e){h&&(l[0]=s.r>>3);for(var u=IT[e-1],d=u>>13,p=u&8191,m=(1<<t)-1,A=s.p||new os(32768),g=s.h||new os(m+1),y=Math.ceil(t/3),_=2*y,v=function(Se){return(r[Se]^r[Se+1]<<y^r[Se+2]<<_)&m},b=new Dd(25e3),T=new os(288),E=new os(32),M=0,S=0,w=s.i||0,C=0,D=s.w||0,O=0;w+2<a;++w){var F=v(w),G=w&32767,j=g[F];if(A[G]=j,g[F]=G,D<=w){var W=a-w;if((M>7e3||C>24576)&&(W>423||!c)){h=L0(r,l,0,b,T,E,S,C,O,w-O,h),C=M=S=0,O=w;for(var K=0;K<286;++K)T[K]=0;for(var K=0;K<30;++K)E[K]=0}var q=2,oe=0,re=p,Ce=G-j&32767;if(W>2&&F==v(w-Ce))for(var Ie=Math.min(d,W)-1,Ue=Math.min(32767,w),te=Math.min(258,W);Ce<=Ue&&--re&&G!=j;){if(r[w+q]==r[w+q-Ce]){for(var ce=0;ce<te&&r[w+ce]==r[w+ce-Ce];++ce);if(ce>q){if(q=ce,oe=Ce,ce>Ie)break;for(var me=Math.min(Ce,ce-2),we=0,K=0;K<me;++K){var je=w-Ce+K&32767,ht=A[je],Ze=je-ht&32767;Ze>we&&(we=Ze,j=je)}}}G=j,j=A[G],Ce+=G-j&32767}if(oe){b[C++]=268435456|Km[q]<<18|D0[oe];var Y=Km[q]&31,fe=D0[oe]&31;S+=lh[Y]+ch[fe],++T[257+Y],++E[fe],D=w+q,++M}else b[C++]=r[w],++T[r[w]]}}for(w=Math.max(w,D);w<a;++w)b[C++]=r[w],++T[r[w]];h=L0(r,l,c,b,T,E,S,C,O,w-O,h),c||(s.r=h&7|l[h/8|0]<<3,h-=7,s.h=g,s.p=A,s.i=w,s.w=D)}else{for(var w=s.w||0;w<a+c;w+=65535){var he=w+65535;he>=a&&(l[h/8|0]=c,he=a),h=B0(l,h+1,r.subarray(w,he))}s.i=a}return $s(o,0,i+uh(h)+n)},DT=(function(){for(var r=new Int32Array(256),e=0;e<256;++e){for(var t=e,i=9;--i;)t=(t&1&&-306674912)^t>>>1;r[e]=t}return r})(),ph=function(){var r=-1;return{p:function(e){for(var t=r,i=0;i<e.length;++i)t=DT[t&255^e[i]]^t>>>8;r=t},d:function(){return~r}}},ig=function(){var r=1,e=0;return{p:function(t){for(var i=r,n=e,s=t.length|0,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)n+=i+=t[a];i=(i&65535)+15*(i>>16),n=(n&65535)+15*(n>>16)}r=i,e=n},d:function(){return r%=65521,e%=65521,(r&255)<<24|(r&65280)<<8|(e&255)<<8|e>>8}}},Sl=function(r,e,t,i,n){if(!n&&(n={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),a=new St(s.length+r.length);a.set(s),a.set(r,s.length),r=a,n.w=s.length}return PT(r,e.level==null?6:e.level,e.mem==null?n.l?Math.ceil(Math.max(8,Math.min(13,Math.log(r.length)))*1.5):20:12+e.mem,t,i,n)},Od=function(r,e){var t={};for(var i in r)t[i]=r[i];for(var i in e)t[i]=e[i];return t},RT=function(r,e,t){for(var i=r(),n=r.toString(),s=n.slice(n.indexOf("[")+1,n.lastIndexOf("]")).replace(/\s+/g,"").split(","),a=0;a<i.length;++a){var o=i[a],l=s[a];if(typeof o=="function"){e+=";"+l+"=";var c=o.toString();if(o.prototype)if(c.indexOf("[native code]")!=-1){var h=c.indexOf(" ",8)+1;e+=c.slice(h,c.indexOf("(",h))}else{e+=c;for(var u in o.prototype)e+=";"+l+".prototype."+u+"="+o.prototype[u].toString()}else e+=c}else t[l]=o}return e},ng=[],qG=function(r){var e=[];for(var t in r)r[t].buffer&&e.push((r[t]=new r[t].constructor(r[t])).buffer);return e},BT=function(r,e,t,i){if(!ng[t]){for(var n="",s={},a=r.length-1,o=0;o<a;++o)n=RT(r[o],n,s);ng[t]={c:RT(r[a],n,s),e:s}}var l=Od({},ng[t].e);return jG(ng[t].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+e.toString()+"}",t,l,qG(l),i)},mh=function(){return[St,os,Dd,lh,ch,Rd,P0,CT,ST,MT,Bd,TT,Xs,Jm,Ys,Zm,uh,$s,Je,Ld,vh,Ao,O0]},gh=function(){return[St,os,Dd,lh,ch,Rd,Km,D0,xT,Sa,ET,hh,Bd,IT,go,Xs,Gr,dh,eg,tg,R0,fh,B0,L0,uh,$s,PT,Sl,Ud,Ao]},LT=function(){return[F0,k0,oi,ph,DT]},OT=function(){return[N0,NT]},UT=function(){return[G0,oi,ig]},FT=function(){return[z0]},Ao=function(r){return postMessage(r,[r.buffer])},O0=function(r){return r&&{out:r.size&&new St(r.size),dictionary:r.dictionary}},Ah=function(r,e,t,i,n,s){var a=BT(t,i,n,function(o,l){a.terminate(),s(o,l)});return a.postMessage([r,e],e.consume?[r.buffer]:[]),function(){a.terminate()}},Ks=function(r){return r.ondata=function(e,t){return postMessage([e,t],[e.buffer])},function(e){e.data.length?(r.push(e.data[0],e.data[1]),postMessage([e.data[0].length])):r.flush()}},yh=function(r,e,t,i,n,s,a){var o,l=BT(r,i,n,function(c,h){c?(l.terminate(),e.ondata.call(e,c)):Array.isArray(h)?h.length==1?(e.queuedSize-=h[0],e.ondrain&&e.ondrain(h[0])):(h[1]&&l.terminate(),e.ondata.call(e,c,h[0],h[1])):a(h)});l.postMessage(t),e.queuedSize=0,e.push=function(c,h){e.ondata||Je(5),o&&e.ondata(Je(4,0,1),null,!!h),e.queuedSize+=c.length,l.postMessage([c,o=h],[c.buffer])},e.terminate=function(){l.terminate()},s&&(e.flush=function(){l.postMessage([])})},ls=function(r,e){return r[e]|r[e+1]<<8},ln=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},U0=function(r,e){return ln(r,e)+ln(r,e+4)*4294967296},oi=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8},F0=function(r,e){var t=e.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=e.level<2?4:e.level==9?2:0,r[9]=3,e.mtime!=0&&oi(r,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),t){r[3]=8;for(var i=0;i<=t.length;++i)r[i+10]=t.charCodeAt(i)}},N0=function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&Je(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var i=(e>>3&1)+(e>>4&1);i>0;i-=!r[t++]);return t+(e&2)},NT=function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},k0=function(r){return 10+(r.filename?r.filename.length+1:0)},G0=function(r,e){var t=e.level,i=t==0?0:t<6?1:t==9?3:2;if(r[0]=120,r[1]=i<<6|(e.dictionary&&32),r[1]|=31-(r[0]<<8|r[1])%31,e.dictionary){var n=ig();n.p(e.dictionary),oi(r,2,n.d())}},z0=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Je(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&Je(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function El(r,e){return typeof r=="function"&&(e=r,r={}),this.ondata=e,r}var Js=(function(){function r(e,t){if(typeof e=="function"&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new St(98304),this.o.dictionary){var i=this.o.dictionary.subarray(-32768);this.b.set(i,32768-i.length),this.s.i=32768-i.length}}return r.prototype.p=function(e,t){this.ondata(Sl(e,this.o,0,0,this.s),t)},r.prototype.push=function(e,t){this.ondata||Je(5),this.s.l&&Je(4);var i=e.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var n=new St(i&-32768);n.set(this.b.subarray(0,this.s.z)),this.b=n}var s=this.b.length-this.s.z;this.b.set(e.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(s),32768),this.s.z=e.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=t&1,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},r.prototype.flush=function(){this.ondata||Je(5),this.s.l&&Je(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},r})(),kT=(function(){function r(e,t){yh([gh,function(){return[Ks,Js]}],this,El.call(this,e,t),function(i){var n=new Js(i.data);onmessage=Ks(n)},6,1)}return r})();function GT(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),Ah(r,e,[gh],function(i){return Ao(Ud(i.data[0],i.data[1]))},0,t)}function Ud(r,e){return Sl(r,e||{},0,0)}var _s=(function(){function r(e,t){typeof e=="function"&&(t=e,e={}),this.ondata=t;var i=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:i?i.length:0},this.o=new St(32768),this.p=new St(0),i&&this.o.set(i)}return r.prototype.e=function(e){if(this.ondata||Je(5),this.d&&Je(4),!this.p.length)this.p=e;else if(e.length){var t=new St(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},r.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,i=Ld(this.p,this.s,this.o);this.ondata($s(i,t,this.s.b),this.d),this.o=$s(i,this.s.b-32768),this.s.b=this.o.length,this.p=$s(this.p,this.s.p/8|0),this.s.p&=7},r.prototype.push=function(e,t){this.e(e),this.c(t)},r})(),V0=(function(){function r(e,t){yh([mh,function(){return[Ks,_s]}],this,El.call(this,e,t),function(i){var n=new _s(i.data);onmessage=Ks(n)},7,0)}return r})();function H0(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),Ah(r,e,[mh],function(i){return Ao(vh(i.data[0],O0(i.data[1])))},1,t)}function vh(r,e){return Ld(r,{i:2},e&&e.out,e&&e.dictionary)}var sg=(function(){function r(e,t){this.c=ph(),this.l=0,this.v=1,Js.call(this,e,t)}return r.prototype.push=function(e,t){this.c.p(e),this.l+=e.length,Js.prototype.push.call(this,e,t)},r.prototype.p=function(e,t){var i=Sl(e,this.o,this.v&&k0(this.o),t&&8,this.s);this.v&&(F0(i,this.o),this.v=0),t&&(oi(i,i.length-8,this.c.d()),oi(i,i.length-4,this.l)),this.ondata(i,t)},r.prototype.flush=function(){Js.prototype.flush.call(this)},r})(),zT=(function(){function r(e,t){yh([gh,LT,function(){return[Ks,Js,sg]}],this,El.call(this,e,t),function(i){var n=new sg(i.data);onmessage=Ks(n)},8,1)}return r})();function VT(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),Ah(r,e,[gh,LT,function(){return[rg]}],function(i){return Ao(rg(i.data[0],i.data[1]))},2,t)}function rg(r,e){e||(e={});var t=ph(),i=r.length;t.p(r);var n=Sl(r,e,k0(e),8),s=n.length;return F0(n,e),oi(n,s-8,t.d()),oi(n,s-4,i),n}var ag=(function(){function r(e,t){this.v=1,this.r=0,_s.call(this,e,t)}return r.prototype.push=function(e,t){if(_s.prototype.e.call(this,e),this.r+=e.length,this.v){var i=this.p.subarray(this.v-1),n=i.length>3?N0(i):4;if(n>i.length){if(!t)return}else this.v>1&&this.onmember&&this.onmember(this.r-i.length);this.p=i.subarray(n),this.v=0}_s.prototype.c.call(this,t),this.s.f&&!this.s.l&&!t&&(this.v=uh(this.s.p)+9,this.s={i:0},this.o=new St(0),this.push(new St(0),t))},r})(),HT=(function(){function r(e,t){var i=this;yh([mh,OT,function(){return[Ks,_s,ag]}],this,El.call(this,e,t),function(n){var s=new ag(n.data);s.onmember=function(a){return postMessage(a)},onmessage=Ks(s)},9,0,function(n){return i.onmember&&i.onmember(n)})}return r})();function QT(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),Ah(r,e,[mh,OT,function(){return[og]}],function(i){return Ao(og(i.data[0],i.data[1]))},3,t)}function og(r,e){var t=N0(r);return t+8>r.length&&Je(6,"invalid gzip data"),Ld(r.subarray(t,-8),{i:2},e&&e.out||new St(NT(r)),e&&e.dictionary)}var Q0=(function(){function r(e,t){this.c=ig(),this.v=1,Js.call(this,e,t)}return r.prototype.push=function(e,t){this.c.p(e),Js.prototype.push.call(this,e,t)},r.prototype.p=function(e,t){var i=Sl(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(G0(i,this.o),this.v=0),t&&oi(i,i.length-4,this.c.d()),this.ondata(i,t)},r.prototype.flush=function(){Js.prototype.flush.call(this)},r})(),XG=(function(){function r(e,t){yh([gh,UT,function(){return[Ks,Js,Q0]}],this,El.call(this,e,t),function(i){var n=new Q0(i.data);onmessage=Ks(n)},10,1)}return r})();function YG(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),Ah(r,e,[gh,UT,function(){return[lg]}],function(i){return Ao(lg(i.data[0],i.data[1]))},4,t)}function lg(r,e){e||(e={});var t=ig();t.p(r);var i=Sl(r,e,e.dictionary?6:2,4);return G0(i,e),oi(i,i.length-4,t.d()),i}var cg=(function(){function r(e,t){_s.call(this,e,t),this.v=e&&e.dictionary?2:1}return r.prototype.push=function(e,t){if(_s.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(z0(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&Je(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),_s.prototype.c.call(this,t)},r})(),jT=(function(){function r(e,t){yh([mh,FT,function(){return[Ks,_s,cg]}],this,El.call(this,e,t),function(i){var n=new cg(i.data);onmessage=Ks(n)},11,0)}return r})();function WT(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),Ah(r,e,[mh,FT,function(){return[Ea]}],function(i){return Ao(Ea(i.data[0],O0(i.data[1])))},5,t)}function Ea(r,e){return Ld(r.subarray(z0(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}var j0=(function(){function r(e,t){this.o=El.call(this,e,t)||{},this.G=ag,this.I=_s,this.Z=cg}return r.prototype.i=function(){var e=this;this.s.ondata=function(t,i){e.ondata(t,i)}},r.prototype.push=function(e,t){if(this.ondata||Je(5),this.s)this.s.push(e,t);else{if(this.p&&this.p.length){var i=new St(this.p.length+e.length);i.set(this.p),i.set(e,this.p.length)}else this.p=e;this.p.length>2&&(this.s=this.p[0]==31&&this.p[1]==139&&this.p[2]==8?new this.G(this.o):(this.p[0]&15)!=8||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(this.o):new this.Z(this.o),this.i(),this.s.push(this.p,t),this.p=null)}},r})(),$G=(function(){function r(e,t){j0.call(this,e,t),this.queuedSize=0,this.G=HT,this.I=V0,this.Z=jT}return r.prototype.i=function(){var e=this;this.s.ondata=function(t,i,n){e.ondata(t,i,n)},this.s.ondrain=function(t){e.queuedSize-=t,e.ondrain&&e.ondrain(t)}},r.prototype.push=function(e,t){this.queuedSize+=e.length,j0.prototype.push.call(this,e,t)},r})();function KG(r,e,t){return t||(t=e,e={}),typeof t!="function"&&Je(7),r[0]==31&&r[1]==139&&r[2]==8?QT(r,e,t):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?H0(r,e,t):WT(r,e,t)}function JG(r,e){return r[0]==31&&r[1]==139&&r[2]==8?og(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?vh(r,e):Ea(r,e)}var W0=function(r,e,t,i){for(var n in r){var s=r[n],a=e+n,o=i;Array.isArray(s)&&(o=Od(i,s[1]),s=s[0]),s instanceof St?t[a]=[s,o]:(t[a+="/"]=[new St(0),o],W0(s,a,t,i))}},qT=typeof TextEncoder<"u"&&new TextEncoder,q0=typeof TextDecoder<"u"&&new TextDecoder,XT=0;try{q0.decode(go,{stream:!0}),XT=1}catch{}var YT=function(r){for(var e="",t=0;;){var i=r[t++],n=(i>127)+(i>223)+(i>239);if(t+n>r.length)return{s:e,r:$s(r,t-1)};n?n==3?(i=((i&15)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):n&1?e+=String.fromCharCode((i&31)<<6|r[t++]&63):e+=String.fromCharCode((i&15)<<12|(r[t++]&63)<<6|r[t++]&63):e+=String.fromCharCode(i)}},ZG=(function(){function r(e){this.ondata=e,XT?this.t=new TextDecoder:this.p=go}return r.prototype.push=function(e,t){if(this.ondata||Je(5),t=!!t,this.t){this.ondata(this.t.decode(e,{stream:!0}),t),t&&(this.t.decode().length&&Je(8),this.t=null);return}this.p||Je(4);var i=new St(this.p.length+e.length);i.set(this.p),i.set(e,this.p.length);var n=YT(i),s=n.s,a=n.r;t?(a.length&&Je(8),this.p=null):this.p=a,this.ondata(s,t)},r})(),ez=(function(){function r(e){this.ondata=e}return r.prototype.push=function(e,t){this.ondata||Je(5),this.d&&Je(4),this.ondata(yo(e),this.d=t||!1)},r})();function yo(r,e){if(e){for(var t=new St(r.length),i=0;i<r.length;++i)t[i]=r.charCodeAt(i);return t}if(qT)return qT.encode(r);for(var n=r.length,s=new St(r.length+(r.length>>1)),a=0,o=function(h){s[a++]=h},i=0;i<n;++i){if(a+5>s.length){var l=new St(a+8+(n-i<<1));l.set(s),s=l}var c=r.charCodeAt(i);c<128||e?o(c):c<2048?(o(192|c>>6),o(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|r.charCodeAt(++i)&1023,o(240|c>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|c&63)):(o(224|c>>12),o(128|c>>6&63),o(128|c&63))}return $s(s,0,a)}function Fd(r,e){if(e){for(var t="",i=0;i<r.length;i+=16384)t+=String.fromCharCode.apply(null,r.subarray(i,i+16384));return t}else{if(q0)return q0.decode(r);var n=YT(r),s=n.s,t=n.r;return t.length&&Je(8),s}}var $T=function(r){return r==1?3:r<6?2:r==9?1:0},KT=function(r,e){return e+30+ls(r,e+26)+ls(r,e+28)},JT=function(r,e,t){var i=ls(r,e+28),n=Fd(r.subarray(e+46,e+46+i),!(ls(r,e+8)&2048)),s=e+46+i,a=ln(r,e+20),o=t&&a==4294967295?ZT(r,s):[a,ln(r,e+24),ln(r,e+42)],l=o[0],c=o[1],h=o[2];return[ls(r,e+10),l,c,n,s+ls(r,e+30)+ls(r,e+32),h]},ZT=function(r,e){for(;ls(r,e)!=1;e+=4+ls(r,e+2));return[U0(r,e+12),U0(r,e+4),U0(r,e+20)]},vo=function(r){var e=0;if(r)for(var t in r){var i=r[t].length;i>65535&&Je(9),e+=i+4}return e},_h=function(r,e,t,i,n,s,a,o){var l=i.length,c=t.extra,h=o&&o.length,u=vo(c);oi(r,e,a!=null?33639248:67324752),e+=4,a!=null&&(r[e++]=20,r[e++]=t.os),r[e]=20,e+=2,r[e++]=t.flag<<1|(s<0&&8),r[e++]=n&&8,r[e++]=t.compression&255,r[e++]=t.compression>>8;var d=new Date(t.mtime==null?Date.now():t.mtime),p=d.getFullYear()-1980;if((p<0||p>119)&&Je(10),oi(r,e,p<<25|d.getMonth()+1<<21|d.getDate()<<16|d.getHours()<<11|d.getMinutes()<<5|d.getSeconds()>>1),e+=4,s!=-1&&(oi(r,e,t.crc),oi(r,e+4,s<0?-s-2:s),oi(r,e+8,t.size)),oi(r,e+12,l),oi(r,e+14,u),e+=16,a!=null&&(oi(r,e,h),oi(r,e+6,t.attrs),oi(r,e+10,a),e+=14),r.set(i,e),e+=l,u)for(var m in c){var A=c[m],g=A.length;oi(r,e,+m),oi(r,e+2,g),r.set(A,e+4),e+=4+g}return h&&(r.set(o,e),e+=h),e},X0=function(r,e,t,i,n){oi(r,e,101010256),oi(r,e+8,t),oi(r,e+10,t),oi(r,e+12,i),oi(r,e+16,n)},Nd=(function(){function r(e){this.filename=e,this.c=ph(),this.size=0,this.compression=0}return r.prototype.process=function(e,t){this.ondata(null,e,t)},r.prototype.push=function(e,t){this.ondata||Je(5),this.c.p(e),this.size+=e.length,t&&(this.crc=this.c.d()),this.process(e,t||!1)},r})(),tz=(function(){function r(e,t){var i=this;t||(t={}),Nd.call(this,e),this.d=new Js(t,function(n,s){i.ondata(null,n,s)}),this.compression=8,this.flag=$T(t.level)}return r.prototype.process=function(e,t){try{this.d.push(e,t)}catch(i){this.ondata(i,null,t)}},r.prototype.push=function(e,t){Nd.prototype.push.call(this,e,t)},r})(),iz=(function(){function r(e,t){var i=this;t||(t={}),Nd.call(this,e),this.d=new kT(t,function(n,s,a){i.ondata(n,s,a)}),this.compression=8,this.flag=$T(t.level),this.terminate=this.d.terminate}return r.prototype.process=function(e,t){this.d.push(e,t)},r.prototype.push=function(e,t){Nd.prototype.push.call(this,e,t)},r})(),nz=(function(){function r(e){this.ondata=e,this.u=[],this.d=1}return r.prototype.add=function(e){var t=this;if(this.ondata||Je(5),this.d&2)this.ondata(Je(4+(this.d&1)*8,0,1),null,!1);else{var i=yo(e.filename),n=i.length,s=e.comment,a=s&&yo(s),o=n!=e.filename.length||a&&s.length!=a.length,l=n+vo(e.extra)+30;n>65535&&this.ondata(Je(11,0,1),null,!1);var c=new St(l);_h(c,0,e,i,o,-1);var h=[c],u=function(){for(var g=0,y=h;g<y.length;g++){var _=y[g];t.ondata(null,_,!1)}h=[]},d=this.d;this.d=0;var p=this.u.length,m=Od(e,{f:i,u:o,o:a,t:function(){e.terminate&&e.terminate()},r:function(){if(u(),d){var g=t.u[p+1];g?g.r():t.d=1}d=1}}),A=0;e.ondata=function(g,y,_){if(g)t.ondata(g,y,_),t.terminate();else if(A+=y.length,h.push(y),_){var v=new St(16);oi(v,0,134695760),oi(v,4,e.crc),oi(v,8,A),oi(v,12,e.size),h.push(v),m.c=A,m.b=l+A+16,m.crc=e.crc,m.size=e.size,d&&m.r(),d=1}else d&&u()},this.u.push(m)}},r.prototype.end=function(){var e=this;if(this.d&2){this.ondata(Je(4+(this.d&1)*8,0,1),null,!0);return}this.d?this.e():this.u.push({r:function(){e.d&1&&(e.u.splice(-1,1),e.e())},t:function(){}}),this.d=3},r.prototype.e=function(){for(var e=0,t=0,i=0,n=0,s=this.u;n<s.length;n++){var a=s[n];i+=46+a.f.length+vo(a.extra)+(a.o?a.o.length:0)}for(var o=new St(i+22),l=0,c=this.u;l<c.length;l++){var a=c[l];_h(o,e,a,a.f,a.u,-a.c-2,t,a.o),e+=46+a.f.length+vo(a.extra)+(a.o?a.o.length:0),t+=a.b}X0(o,e,this.u.length,i,t),this.ondata(null,o,!0),this.d=2},r.prototype.terminate=function(){for(var e=0,t=this.u;e<t.length;e++){var i=t[e];i.t()}this.d=2},r})();function sz(r,e,t){t||(t=e,e={}),typeof t!="function"&&Je(7);var i={};W0(r,"",i,e);var n=Object.keys(i),s=n.length,a=0,o=0,l=s,c=new Array(s),h=[],u=function(){for(var g=0;g<h.length;++g)h[g]()},d=function(g,y){ug(function(){t(g,y)})};ug(function(){d=t});var p=function(){var g=new St(o+22),y=a,_=o-a;o=0;for(var v=0;v<l;++v){var b=c[v];try{var T=b.c.length;_h(g,o,b,b.f,b.u,T);var E=30+b.f.length+vo(b.extra),M=o+E;g.set(b.c,M),_h(g,a,b,b.f,b.u,T,o,b.m),a+=16+E+(b.m?b.m.length:0),o=M+T}catch(S){return d(S,null)}}X0(g,a,c.length,_,y),d(null,g)};s||p();for(var m=function(g){var y=n[g],_=i[y],v=_[0],b=_[1],T=ph(),E=v.length;T.p(v);var M=yo(y),S=M.length,w=b.comment,C=w&&yo(w),D=C&&C.length,O=vo(b.extra),F=b.level==0?0:8,G=function(j,W){if(j)u(),d(j,null);else{var K=W.length;c[g]=Od(b,{size:E,crc:T.d(),c:W,f:M,m:C,u:S!=y.length||C&&w.length!=D,compression:F}),a+=30+S+O+K,o+=76+2*(S+O)+(D||0)+K,--s||p()}};if(S>65535&&G(Je(11,0,1),null),!F)G(null,v);else if(E<16e4)try{G(null,Ud(v,b))}catch(j){G(j,null)}else h.push(GT(v,b,G))},A=0;A<l;++A)m(A);return u}function hg(r,e){e||(e={});var t={},i=[];W0(r,"",t,e);var n=0,s=0;for(var a in t){var o=t[a],l=o[0],c=o[1],h=c.level==0?0:8,u=yo(a),d=u.length,p=c.comment,m=p&&yo(p),A=m&&m.length,g=vo(c.extra);d>65535&&Je(11);var y=h?Ud(l,c):l,_=y.length,v=ph();v.p(l),i.push(Od(c,{size:l.length,crc:v.d(),c:y,f:u,m,u:d!=a.length||m&&p.length!=A,o:n,compression:h})),n+=30+d+g+_,s+=76+2*(d+g)+(A||0)+_}for(var b=new St(s+22),T=n,E=s-n,M=0;M<i.length;++M){var u=i[M];_h(b,u.o,u,u.f,u.u,u.c.length);var S=30+u.f.length+vo(u.extra);b.set(u.c,u.o+S),_h(b,n,u,u.f,u.u,u.c.length,u.o,u.m),n+=16+S+(u.m?u.m.length:0)}return X0(b,n,i.length,E,T),b}var e1=(function(){function r(){}return r.prototype.push=function(e,t){this.ondata(null,e,t)},r.compression=0,r})(),rz=(function(){function r(){var e=this;this.i=new _s(function(t,i){e.ondata(null,t,i)})}return r.prototype.push=function(e,t){try{this.i.push(e,t)}catch(i){this.ondata(i,null,t)}},r.compression=8,r})(),az=(function(){function r(e,t){var i=this;t<32e4?this.i=new _s(function(n,s){i.ondata(null,n,s)}):(this.i=new V0(function(n,s,a){i.ondata(n,s,a)}),this.terminate=this.i.terminate)}return r.prototype.push=function(e,t){this.i.terminate&&(e=$s(e,0)),this.i.push(e,t)},r.compression=8,r})(),oz=(function(){function r(e){this.onfile=e,this.k=[],this.o={0:e1},this.p=go}return r.prototype.push=function(e,t){var i=this;if(this.onfile||Je(5),this.p||Je(4),this.c>0){var n=Math.min(this.c,e.length),s=e.subarray(0,n);if(this.c-=n,this.d?this.d.push(s,!this.c):this.k[0].push(s),e=e.subarray(n),e.length)return this.push(e,t)}else{var a=0,o=0,l=void 0,c=void 0;this.p.length?e.length?(c=new St(this.p.length+e.length),c.set(this.p),c.set(e,this.p.length)):c=this.p:c=e;for(var h=c.length,u=this.c,d=u&&this.d,p=function(){var y,_=ln(c,o);if(_==67324752){a=1,l=o,m.d=null,m.c=0;var v=ls(c,o+6),b=ls(c,o+8),T=v&2048,E=v&8,M=ls(c,o+26),S=ls(c,o+28);if(h>o+30+M+S){var w=[];m.k.unshift(w),a=2;var C=ln(c,o+18),D=ln(c,o+22),O=Fd(c.subarray(o+30,o+=30+M),!T);C==4294967295?(y=E?[-2]:ZT(c,o),C=y[0],D=y[1]):E&&(C=-1),o+=S,m.c=C;var F,G={name:O,compression:b,start:function(){if(G.ondata||Je(5),!C)G.ondata(null,go,!0);else{var j=i.o[b];j||G.ondata(Je(14,"unknown compression type "+b,1),null,!1),F=C<0?new j(O):new j(O,C,D),F.ondata=function(oe,re,Ce){G.ondata(oe,re,Ce)};for(var W=0,K=w;W<K.length;W++){var q=K[W];F.push(q,!1)}i.k[0]==w&&i.c?i.d=F:F.push(go,!0)}},terminate:function(){F&&F.terminate&&F.terminate()}};C>=0&&(G.size=C,G.originalSize=D),m.onfile(G)}return"break"}else if(u){if(_==134695760)return l=o+=12+(u==-2&&8),a=3,m.c=0,"break";if(_==33639248)return l=o-=4,a=3,m.c=0,"break"}},m=this;o<h-4;++o){var A=p();if(A==="break")break}if(this.p=go,u<0){var g=a?c.subarray(0,l-12-(u==-2&&8)-(ln(c,l-16)==134695760&&4)):c.subarray(0,o);d?d.push(g,!!a):this.k[+(a==2)].push(g)}if(a&2)return this.push(c.subarray(o),t);this.p=c.subarray(o)}t&&(this.c&&Je(13),this.p=null)},r.prototype.register=function(e){this.o[e.compression]=e},r})(),ug=typeof queueMicrotask=="function"?queueMicrotask:typeof setTimeout=="function"?setTimeout:function(r){r()};function lz(r,e,t){t||(t=e,e={}),typeof t!="function"&&Je(7);var i=[],n=function(){for(var g=0;g<i.length;++g)i[g]()},s={},a=function(g,y){ug(function(){t(g,y)})};ug(function(){a=t});for(var o=r.length-22;ln(r,o)!=101010256;--o)if(!o||r.length-o>65558)return a(Je(13,0,1),null),n;var l=ls(r,o+8);if(l){var c=l,h=ln(r,o+16),u=h==4294967295||c==65535;if(u){var d=ln(r,o-12);u=ln(r,d)==101075792,u&&(c=l=ln(r,d+32),h=ln(r,d+48))}for(var p=e&&e.filter,m=function(g){var y=JT(r,h,u),_=y[0],v=y[1],b=y[2],T=y[3],E=y[4],M=y[5],S=KT(r,M);h=E;var w=function(D,O){D?(n(),a(D,null)):(O&&(s[T]=O),--l||a(null,s))};if(!p||p({name:T,size:v,originalSize:b,compression:_}))if(!_)w(null,$s(r,S,S+v));else if(_==8){var C=r.subarray(S,S+v);if(b<524288||v>.8*b)try{w(null,vh(C,{out:new St(b)}))}catch(D){w(D,null)}else i.push(H0(C,{size:b},w))}else w(Je(14,"unknown compression type "+_,1),null);else w(null,null)},A=0;A<c;++A)m(A)}else a(null,{});return n}function Y0(r,e){for(var t={},i=r.length-22;ln(r,i)!=101010256;--i)(!i||r.length-i>65558)&&Je(13);var n=ls(r,i+8);if(!n)return{};var s=ln(r,i+16),a=s==4294967295||n==65535;if(a){var o=ln(r,i-12);a=ln(r,o)==101075792,a&&(n=ln(r,o+32),s=ln(r,o+48))}for(var l=e&&e.filter,c=0;c<n;++c){var h=JT(r,s,a),u=h[0],d=h[1],p=h[2],m=h[3],A=h[4],g=h[5],y=KT(r,g);s=A,(!l||l({name:m,size:d,originalSize:p,compression:u}))&&(u?u==8?t[m]=vh(r.subarray(y,y+d),{out:new St(p)}):Je(14,"unknown compression type "+u):t[m]=$s(r,y,y+d))}return t}function t1(r,e,t){const i=t.length-r-1;if(e>=t[i])return i-1;if(e<=t[r])return r;let n=r,s=i,a=Math.floor((n+s)/2);for(;e<t[a]||e>=t[a+1];)e<t[a]?s=a:n=a,a=Math.floor((n+s)/2);return a}function cz(r,e,t,i){const n=[],s=[],a=[];n[0]=1;for(let o=1;o<=t;++o){s[o]=e-i[r+1-o],a[o]=i[r+o]-e;let l=0;for(let c=0;c<o;++c){const h=a[c+1],u=s[o-c],d=n[c]/(h+u);n[c]=l+h*d,l=u*d}n[o]=l}return n}function hz(r,e,t,i){const n=t1(r,i,e),s=cz(n,i,r,e),a=new rt(0,0,0,0);for(let o=0;o<=r;++o){const l=t[n-r+o],c=s[o],h=l.w*c;a.x+=l.x*h,a.y+=l.y*h,a.z+=l.z*h,a.w+=l.w*c}return a}function uz(r,e,t,i,n){const s=[];for(let u=0;u<=t;++u)s[u]=0;const a=[];for(let u=0;u<=i;++u)a[u]=s.slice(0);const o=[];for(let u=0;u<=t;++u)o[u]=s.slice(0);o[0][0]=1;const l=s.slice(0),c=s.slice(0);for(let u=1;u<=t;++u){l[u]=e-n[r+1-u],c[u]=n[r+u]-e;let d=0;for(let p=0;p<u;++p){const m=c[p+1],A=l[u-p];o[u][p]=m+A;const g=o[p][u-1]/o[u][p];o[p][u]=d+m*g,d=A*g}o[u][u]=d}for(let u=0;u<=t;++u)a[0][u]=o[u][t];for(let u=0;u<=t;++u){let d=0,p=1;const m=[];for(let A=0;A<=t;++A)m[A]=s.slice(0);m[0][0]=1;for(let A=1;A<=i;++A){let g=0;const y=u-A,_=t-A;u>=A&&(m[p][0]=m[d][0]/o[_+1][y],g=m[p][0]*o[y][_]);const v=y>=-1?1:-y,b=u-1<=_?A-1:t-u;for(let E=v;E<=b;++E)m[p][E]=(m[d][E]-m[d][E-1])/o[_+1][y+E],g+=m[p][E]*o[y+E][_];u<=_&&(m[p][A]=-m[d][A-1]/o[_+1][u],g+=m[p][A]*o[u][_]),a[A][u]=g;const T=d;d=p,p=T}}let h=t;for(let u=1;u<=i;++u){for(let d=0;d<=t;++d)a[u][d]*=h;h*=t-u}return a}function dz(r,e,t,i,n){const s=n<r?n:r,a=[],o=t1(r,i,e),l=uz(o,i,r,s,e),c=[];for(let h=0;h<t.length;++h){const u=t[h].clone(),d=u.w;u.x*=d,u.y*=d,u.z*=d,c[h]=u}for(let h=0;h<=s;++h){const u=c[o-r].clone().multiplyScalar(l[h][0]);for(let d=1;d<=r;++d)u.add(c[o-r+d].clone().multiplyScalar(l[h][d]));a[h]=u}for(let h=s+1;h<=n+1;++h)a[h]=new rt(0,0,0);return a}function fz(r,e){let t=1;for(let n=2;n<=r;++n)t*=n;let i=1;for(let n=2;n<=e;++n)i*=n;for(let n=2;n<=r-e;++n)i*=n;return t/i}function pz(r){const e=r.length,t=[],i=[];for(let s=0;s<e;++s){const a=r[s];t[s]=new x(a.x,a.y,a.z),i[s]=a.w}const n=[];for(let s=0;s<e;++s){const a=t[s].clone();for(let o=1;o<=s;++o)a.sub(n[s-o].clone().multiplyScalar(fz(s,o)*i[o]));n[s]=a.divideScalar(i[0])}return n}function mz(r,e,t,i,n){const s=dz(r,e,t,i,n);return pz(s)}class gz extends Ps{constructor(e,t,i,n,s){super(),this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=n||0,this.endKnot=s||this.knots.length-1;for(let a=0;a<i.length;++a){const o=i[a];this.controlPoints[a]=new rt(o.x,o.y,o.z,o.w)}}getPoint(e,t=new x){const i=t,n=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),s=hz(this.degree,this.knots,this.controlPoints,n);return s.w!==1&&s.divideScalar(s.w),i.set(s.x,s.y,s.z)}getTangent(e,t=new x){const i=t,n=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),s=mz(this.degree,this.knots,this.controlPoints,n,1);return i.copy(s[1]).normalize(),i}}let It,Xi,Jn;class i1 extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=s.path===""?Rs.extractUrlBase(e):s.path,o=new Zt(this.manager);o.setPath(s.path),o.setResponseType("arraybuffer"),o.setRequestHeader(s.requestHeader),o.setWithCredentials(s.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){n?n(c):console.error(c),s.manager.itemError(e)}},i,n)}parse(e,t){if(wz(e))It=new bz().parse(e);else{const s=l1(e);if(!Cz(s))throw new Error("THREE.FBXLoader: Unknown format.");if(r1(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+r1(s));It=new _z().parse(s)}const i=new to(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),n=new Az(i,this.manager).parse(It);return It=null,Xi=null,Jn=null,n}}class Az{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Xi=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),n=this.parseDeformers(),s=new yz().parse(n);return this.parseScene(n,s,i),Jn}parseConnections(){const e=new Map;return"Connections"in It&&It.Connections.connections.forEach(function(i){const n=i[0],s=i[1],a=i[2];e.has(n)||e.set(n,{parents:[],children:[]});const o={ID:s,relationship:a};e.get(n).parents.push(o),e.has(s)||e.set(s,{parents:[],children:[]});const l={ID:n,relationship:a};e.get(s).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in It.Objects){const i=It.Objects.Video;for(const n in i){const s=i[n],a=parseInt(n);if(e[a]=s.RelativeFilename||s.Filename,"Content"in s){const o=s.Content instanceof ArrayBuffer&&s.Content.byteLength>0,l=typeof s.Content=="string"&&s.Content!=="";if(o||l){const c=this.parseImage(i[n]);t[s.RelativeFilename||s.Filename]=c}}}}for(const i in e){const n=e[i];t[n]!==void 0?e[i]=t[n]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,n=i.slice(i.lastIndexOf(".")+1).toLowerCase();let s;switch(n){case"bmp":s="image/bmp";break;case"jpg":case"jpeg":s="image/jpeg";break;case"png":s="image/png";break;case"tif":s="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),s="image/tga";break;default:console.warn('FBXLoader: Image type "'+n+'" is not supported.');return}if(typeof t=="string")return"data:"+s+";base64,"+t;{const a=new Uint8Array(t);return window.URL.createObjectURL(new Blob([a],{type:s}))}}parseTextures(e){const t=new Map;if("Texture"in It.Objects){const i=It.Objects.Texture;for(const n in i){const s=this.parseTexture(i[n],e);t.set(parseInt(n),s)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const n=e.WrapModeU,s=e.WrapModeV,a=n!==void 0?n.value:0,o=s!==void 0?s.value:0;if(i.wrapS=a===0?Bn:ui,i.wrapT=o===0?Bn:ui,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){let i;const n=this.textureLoader.path,s=Xi.get(e.id).children;s!==void 0&&s.length>0&&t[s[0].ID]!==void 0&&(i=t[s[0].ID],(i.indexOf("blob:")===0||i.indexOf("data:")===0)&&this.textureLoader.setPath(void 0));let a;const o=e.FileName.slice(-3).toLowerCase();if(o==="tga"){const l=this.manager.getHandler(".tga");l===null?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",e.RelativeFilename),a=new Rt):(l.setPath(this.textureLoader.path),a=l.load(i))}else if(o==="dds"){const l=this.manager.getHandler(".dds");l===null?(console.warn("FBXLoader: DDS loader not found, creating placeholder texture for",e.RelativeFilename),a=new Rt):(l.setPath(this.textureLoader.path),a=l.load(i))}else o==="psd"?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",e.RelativeFilename),a=new Rt):a=this.textureLoader.load(i);return this.textureLoader.setPath(n),a}parseMaterials(e){const t=new Map;if("Material"in It.Objects){const i=It.Objects.Material;for(const n in i){const s=this.parseMaterial(i[n],e);s!==null&&t.set(parseInt(n),s)}}return t}parseMaterial(e,t){const i=e.id,n=e.attrName;let s=e.ShadingModel;if(typeof s=="object"&&(s=s.value),!Xi.has(i))return null;const a=this.parseParameters(e,t,i);let o;switch(s.toLowerCase()){case"phong":o=new Ko;break;case"lambert":o=new Cy;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',s),o=new Ko;break}return o.setValues(a),o.name=n,o}parseParameters(e,t,i){const n={};e.BumpFactor&&(n.bumpScale=e.BumpFactor.value),e.Diffuse?n.color=new se().fromArray(e.Diffuse.value).convertSRGBToLinear():e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(n.color=new se().fromArray(e.DiffuseColor.value).convertSRGBToLinear()),e.DisplacementFactor&&(n.displacementScale=e.DisplacementFactor.value),e.Emissive?n.emissive=new se().fromArray(e.Emissive.value).convertSRGBToLinear():e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(n.emissive=new se().fromArray(e.EmissiveColor.value).convertSRGBToLinear()),e.EmissiveFactor&&(n.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),e.Opacity&&(n.opacity=parseFloat(e.Opacity.value)),n.opacity<1&&(n.transparent=!0),e.ReflectionFactor&&(n.reflectivity=e.ReflectionFactor.value),e.Shininess&&(n.shininess=e.Shininess.value),e.Specular?n.specular=new se().fromArray(e.Specular.value).convertSRGBToLinear():e.SpecularColor&&e.SpecularColor.type==="Color"&&(n.specular=new se().fromArray(e.SpecularColor.value).convertSRGBToLinear());const s=this;return Xi.get(i).children.forEach(function(a){const o=a.relationship;switch(o){case"Bump":n.bumpMap=s.getTexture(t,a.ID);break;case"Maya|TEX_ao_map":n.aoMap=s.getTexture(t,a.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":n.map=s.getTexture(t,a.ID),n.map!==void 0&&(n.map.colorSpace=vt);break;case"DisplacementColor":n.displacementMap=s.getTexture(t,a.ID);break;case"EmissiveColor":n.emissiveMap=s.getTexture(t,a.ID),n.emissiveMap!==void 0&&(n.emissiveMap.colorSpace=vt);break;case"NormalMap":case"Maya|TEX_normal_map":n.normalMap=s.getTexture(t,a.ID);break;case"ReflectionColor":n.envMap=s.getTexture(t,a.ID),n.envMap!==void 0&&(n.envMap.mapping=Jr,n.envMap.colorSpace=vt);break;case"SpecularColor":n.specularMap=s.getTexture(t,a.ID),n.specularMap!==void 0&&(n.specularMap.colorSpace=vt);break;case"TransparentColor":case"TransparencyFactor":n.alphaMap=s.getTexture(t,a.ID),n.transparent=!0;break;case"AmbientColor":case"ShininessExponent":case"SpecularFactor":case"VectorDisplacementColor":default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),n}getTexture(e,t){return"LayeredTexture"in It.Objects&&t in It.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Xi.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in It.Objects){const i=It.Objects.Deformer;for(const n in i){const s=i[n],a=Xi.get(parseInt(n));if(s.attrType==="Skin"){const o=this.parseSkeleton(a,i);o.ID=n,a.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=a.parents[0].ID,e[n]=o}else if(s.attrType==="BlendShape"){const o={id:n};o.rawTargets=this.parseMorphTargets(a,i),o.id=n,a.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[n]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(n){const s=t[n.ID];if(s.attrType!=="Cluster")return;const a={ID:n.ID,indices:[],weights:[],transformLink:new pe().fromArray(s.TransformLink.a)};"Indexes"in s&&(a.indices=s.Indexes.a,a.weights=s.Weights.a),i.push(a)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let n=0;n<e.children.length;n++){const s=e.children[n],a=t[s.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!=="BlendShapeChannel")return;o.geoID=Xi.get(parseInt(s.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,i.push(o)}return i}parseScene(e,t,i){Jn=new Ri;const n=this.parseModels(e.skeletons,t,i),s=It.Objects.Model,a=this;n.forEach(function(l){const c=s[l.ID];a.setLookAtProperties(l,c),Xi.get(l.ID).parents.forEach(function(u){const d=n.get(u.ID);d!==void 0&&d.add(l)}),l.parent===null&&Jn.add(l)}),this.bindSkeleton(e.skeletons,t,n),this.addGlobalSceneSettings(),Jn.traverse(function(l){if(l.userData.transformData){l.parent&&(l.userData.transformData.parentMatrix=l.parent.matrix,l.userData.transformData.parentMatrixWorld=l.parent.matrixWorld);const c=a1(l.userData.transformData);l.applyMatrix4(c),l.updateWorldMatrix()}});const o=new vz().parse();Jn.children.length===1&&Jn.children[0].isGroup&&(Jn.children[0].animations=o,Jn=Jn.children[0]),Jn.animations=o}parseModels(e,t,i){const n=new Map,s=It.Objects.Model;for(const a in s){const o=parseInt(a),l=s[a],c=Xi.get(o);let h=this.buildSkeleton(c,e,o,l.attrName);if(!h){switch(l.attrType){case"Camera":h=this.createCamera(c);break;case"Light":h=this.createLight(c);break;case"Mesh":h=this.createMesh(c,t,i);break;case"NurbsCurve":h=this.createCurve(c,t);break;case"LimbNode":case"Root":h=new Pc;break;case"Null":default:h=new Ri;break}h.name=l.attrName?Ct.sanitizeNodeName(l.attrName):"",h.userData.originalName=l.attrName,h.ID=o}this.getTransformData(h,l),n.set(o,h)}return n}buildSkeleton(e,t,i,n){let s=null;return e.parents.forEach(function(a){for(const o in t){const l=t[o];l.rawBones.forEach(function(c,h){if(c.ID===a.ID){const u=s;s=new Pc,s.matrixWorld.copy(c.transformLink),s.name=n?Ct.sanitizeNodeName(n):"",s.userData.originalName=n,s.ID=i,l.bones[h]=s,u!==null&&s.add(u)}})}}),s}createCamera(e){let t,i;if(e.children.forEach(function(n){const s=It.Objects.NodeAttribute[n.ID];s!==void 0&&(i=s)}),i===void 0)t=new ft;else{let n=0;i.CameraProjectionType!==void 0&&i.CameraProjectionType.value===1&&(n=1);let s=1;i.NearPlane!==void 0&&(s=i.NearPlane.value/1e3);let a=1e3;i.FarPlane!==void 0&&(a=i.FarPlane.value/1e3);let o=window.innerWidth,l=window.innerHeight;i.AspectWidth!==void 0&&i.AspectHeight!==void 0&&(o=i.AspectWidth.value,l=i.AspectHeight.value);const c=o/l;let h=45;i.FieldOfView!==void 0&&(h=i.FieldOfView.value);const u=i.FocalLength?i.FocalLength.value:null;switch(n){case 0:t=new Vi(h,c,s,a),u!==null&&t.setFocalLength(u);break;case 1:t=new Mr(-o/2,o/2,l/2,-l/2,s,a);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+n+"."),t=new ft;break}}return t}createLight(e){let t,i;if(e.children.forEach(function(n){const s=It.Objects.NodeAttribute[n.ID];s!==void 0&&(i=s)}),i===void 0)t=new ft;else{let n;i.LightType===void 0?n=0:n=i.LightType.value;let s=16777215;i.Color!==void 0&&(s=new se().fromArray(i.Color.value).convertSRGBToLinear());let a=i.Intensity===void 0?1:i.Intensity.value/100;i.CastLightOnObject!==void 0&&i.CastLightOnObject.value===0&&(a=0);let o=0;i.FarAttenuationEnd!==void 0&&(i.EnableFarAttenuation!==void 0&&i.EnableFarAttenuation.value===0?o=0:o=i.FarAttenuationEnd.value);const l=1;switch(n){case 0:t=new tl(s,a,o,l);break;case 1:t=new il(s,a);break;case 2:let c=Math.PI/3;i.InnerAngle!==void 0&&(c=Ut.degToRad(i.InnerAngle.value));let h=0;i.OuterAngle!==void 0&&(h=Ut.degToRad(i.OuterAngle.value),h=Math.max(h,1)),t=new zc(s,a,o,c,h,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),t=new tl(s,a);break}i.CastShadows!==void 0&&i.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,i){let n,s=null,a=null;const o=[];return e.children.forEach(function(l){t.has(l.ID)&&(s=t.get(l.ID)),i.has(l.ID)&&o.push(i.get(l.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new Ko({name:li.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(a)),"color"in s.attributes&&o.forEach(function(l){l.vertexColors=!0}),s.FBX_Deformer?(n=new np(s,a),n.normalizeSkinWeights()):n=new ye(s,a),n}createCurve(e,t){const i=e.children.reduce(function(s,a){return t.has(a.ID)&&(s=t.get(a.ID)),s},null),n=new Ei({name:li.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new fn(i,n)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=o1(t.RotationOrder.value):i.eulerOrder="ZYX","Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Xi.get(e.ID).children.forEach(function(n){if(n.relationship==="LookAtProperty"){const s=It.Objects.Model[n.ID];if("Lcl_Translation"in s){const a=s.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(a),Jn.add(e.target)):e.lookAt(new x().fromArray(a))}}})}bindSkeleton(e,t,i){const n=this.parsePoseNodes();for(const s in e){const a=e[s];Xi.get(parseInt(a.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Xi.get(c).parents.forEach(function(u){i.has(u.ID)&&i.get(u.ID).bind(new Dc(a.bones),n[u.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in It.Objects){const t=It.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const n=t[i].PoseNode;Array.isArray(n)?n.forEach(function(s){e[s.Node]=new pe().fromArray(s.Matrix.a)}):e[n.Node]=new pe().fromArray(n.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in It){if("AmbientColor"in It.GlobalSettings){const e=It.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],n=e[2];if(t!==0||i!==0||n!==0){const s=new se(t,i,n).convertSRGBToLinear();Jn.add(new Rp(s,1))}}"UnitScaleFactor"in It.GlobalSettings&&(Jn.userData.unitScaleFactor=It.GlobalSettings.UnitScaleFactor.value)}}}class yz{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in It.Objects){const i=It.Objects.Geometry;for(const n in i){const s=Xi.get(parseInt(n)),a=this.parseGeometry(s,i[n],e);t.set(parseInt(n),a)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const n=i.skeletons,s=[],a=e.parents.map(function(u){return It.Objects.Model[u.ID]});if(a.length===0)return;const o=e.children.reduce(function(u,d){return n[d.ID]!==void 0&&(u=n[d.ID]),u},null);e.children.forEach(function(u){i.morphTargets[u.ID]!==void 0&&s.push(i.morphTargets[u.ID])});const l=a[0],c={};"RotationOrder"in l&&(c.eulerOrder=o1(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const h=a1(c);return this.genGeometry(t,o,s,h)}genGeometry(e,t,i,n){const s=new $e;e.attrName&&(s.name=e.attrName);const a=this.parseGeoNode(e,t),o=this.genBuffers(a),l=new Me(o.vertex,3);if(l.applyMatrix4(n),s.setAttribute("position",l),o.colors.length>0&&s.setAttribute("color",new Me(o.colors,3)),t&&(s.setAttribute("skinIndex",new Bf(o.weightsIndices,4)),s.setAttribute("skinWeight",new Me(o.vertexWeights,4)),s.FBX_Deformer=t),o.normal.length>0){const c=new mt().getNormalMatrix(n),h=new Me(o.normal,3);h.applyNormalMatrix(c),s.setAttribute("normal",h)}if(o.uvs.forEach(function(c,h){const u=h===0?"uv":`uv${h}`;s.setAttribute(u,new Me(o.uvs[h],2))}),a.material&&a.material.mappingType!=="AllSame"){let c=o.materialIndex[0],h=0;if(o.materialIndex.forEach(function(u,d){u!==c&&(s.addGroup(h,d-h,c),c=u,h=d)}),s.groups.length>0){const u=s.groups[s.groups.length-1],d=u.start+u.count;d!==o.materialIndex.length&&s.addGroup(d,o.materialIndex.length-d,c)}s.groups.length===0&&s.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(s,e,i,n),s}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let n=0;for(;e.LayerElementUV[n];)e.LayerElementUV[n].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[n])),n++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(n,s){n.indices.forEach(function(a,o){i.weightTable[a]===void 0&&(i.weightTable[a]=[]),i.weightTable[a].push({id:s,weight:n.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,n=0,s=!1,a=[],o=[],l=[],c=[],h=[],u=[];const d=this;return e.vertexIndices.forEach(function(p,m){let A,g=!1;p<0&&(p=p^-1,g=!0);let y=[],_=[];if(a.push(p*3,p*3+1,p*3+2),e.color){const v=dg(m,i,p,e.color);l.push(v[0],v[1],v[2])}if(e.skeleton){if(e.weightTable[p]!==void 0&&e.weightTable[p].forEach(function(v){_.push(v.weight),y.push(v.id)}),_.length>4){s||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),s=!0);const v=[0,0,0,0],b=[0,0,0,0];_.forEach(function(T,E){let M=T,S=y[E];b.forEach(function(w,C,D){if(M>w){D[C]=M,M=w;const O=v[C];v[C]=S,S=O}})}),y=v,_=b}for(;_.length<4;)_.push(0),y.push(0);for(let v=0;v<4;++v)h.push(_[v]),u.push(y[v])}if(e.normal){const v=dg(m,i,p,e.normal);o.push(v[0],v[1],v[2])}e.material&&e.material.mappingType!=="AllSame"&&(A=dg(m,i,p,e.material)[0],A<0&&(d.negativeMaterialIndices=!0,A=0)),e.uv&&e.uv.forEach(function(v,b){const T=dg(m,i,p,v);c[b]===void 0&&(c[b]=[]),c[b].push(T[0]),c[b].push(T[1])}),n++,g&&(d.genFace(t,e,a,A,o,l,c,h,u,n),i++,n=0,a=[],o=[],l=[],c=[],h=[],u=[])}),t}getNormalNewell(e){const t=new x(0,0,0);for(let i=0;i<e.length;i++){const n=e[i],s=e[(i+1)%e.length];t.x+=(n.y-s.y)*(n.z+s.z),t.y+=(n.z-s.z)*(n.x+s.x),t.z+=(n.x-s.x)*(n.y+s.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){const t=this.getNormalNewell(e),n=(Math.abs(t.z)>.5?new x(0,1,0):new x(0,0,1)).cross(t).normalize(),s=t.clone().cross(n).normalize();return{normal:t,tangent:n,bitangent:s}}flattenVertex(e,t,i){return new $(e.dot(t),e.dot(i))}genFace(e,t,i,n,s,a,o,l,c,h){let u;if(h>3){const d=[];for(let g=0;g<i.length;g+=3)d.push(new x(t.vertexPositions[i[g]],t.vertexPositions[i[g+1]],t.vertexPositions[i[g+2]]));const{tangent:p,bitangent:m}=this.getNormalTangentAndBitangent(d),A=[];for(const g of d)A.push(this.flattenVertex(g,p,m));u=or.triangulateShape(A,[])}else u=[[0,1,2]];for(const[d,p,m]of u)e.vertex.push(t.vertexPositions[i[d*3]]),e.vertex.push(t.vertexPositions[i[d*3+1]]),e.vertex.push(t.vertexPositions[i[d*3+2]]),e.vertex.push(t.vertexPositions[i[p*3]]),e.vertex.push(t.vertexPositions[i[p*3+1]]),e.vertex.push(t.vertexPositions[i[p*3+2]]),e.vertex.push(t.vertexPositions[i[m*3]]),e.vertex.push(t.vertexPositions[i[m*3+1]]),e.vertex.push(t.vertexPositions[i[m*3+2]]),t.skeleton&&(e.vertexWeights.push(l[d*4]),e.vertexWeights.push(l[d*4+1]),e.vertexWeights.push(l[d*4+2]),e.vertexWeights.push(l[d*4+3]),e.vertexWeights.push(l[p*4]),e.vertexWeights.push(l[p*4+1]),e.vertexWeights.push(l[p*4+2]),e.vertexWeights.push(l[p*4+3]),e.vertexWeights.push(l[m*4]),e.vertexWeights.push(l[m*4+1]),e.vertexWeights.push(l[m*4+2]),e.vertexWeights.push(l[m*4+3]),e.weightsIndices.push(c[d*4]),e.weightsIndices.push(c[d*4+1]),e.weightsIndices.push(c[d*4+2]),e.weightsIndices.push(c[d*4+3]),e.weightsIndices.push(c[p*4]),e.weightsIndices.push(c[p*4+1]),e.weightsIndices.push(c[p*4+2]),e.weightsIndices.push(c[p*4+3]),e.weightsIndices.push(c[m*4]),e.weightsIndices.push(c[m*4+1]),e.weightsIndices.push(c[m*4+2]),e.weightsIndices.push(c[m*4+3])),t.color&&(e.colors.push(a[d*3]),e.colors.push(a[d*3+1]),e.colors.push(a[d*3+2]),e.colors.push(a[p*3]),e.colors.push(a[p*3+1]),e.colors.push(a[p*3+2]),e.colors.push(a[m*3]),e.colors.push(a[m*3+1]),e.colors.push(a[m*3+2])),t.material&&t.material.mappingType!=="AllSame"&&(e.materialIndex.push(n),e.materialIndex.push(n),e.materialIndex.push(n)),t.normal&&(e.normal.push(s[d*3]),e.normal.push(s[d*3+1]),e.normal.push(s[d*3+2]),e.normal.push(s[p*3]),e.normal.push(s[p*3+1]),e.normal.push(s[p*3+2]),e.normal.push(s[m*3]),e.normal.push(s[m*3+1]),e.normal.push(s[m*3+2])),t.uv&&t.uv.forEach(function(A,g){e.uvs[g]===void 0&&(e.uvs[g]=[]),e.uvs[g].push(o[g][d*2]),e.uvs[g].push(o[g][d*2+1]),e.uvs[g].push(o[g][p*2]),e.uvs[g].push(o[g][p*2+1]),e.uvs[g].push(o[g][m*2]),e.uvs[g].push(o[g][m*2+1])})}addMorphTargets(e,t,i,n){if(i.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];const s=this;i.forEach(function(a){a.rawTargets.forEach(function(o){const l=It.Objects.Geometry[o.geoID];l!==void 0&&s.genMorphGeometry(e,t,l,n,o.name)})})}genMorphGeometry(e,t,i,n,s){const a=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],o=i.Vertices!==void 0?i.Vertices.a:[],l=i.Indexes!==void 0?i.Indexes.a:[],c=e.attributes.position.count*3,h=new Float32Array(c);for(let m=0;m<l.length;m++){const A=l[m]*3;h[A]=o[m*3],h[A+1]=o[m*3+1],h[A+2]=o[m*3+2]}const u={vertexIndices:a,vertexPositions:h},d=this.genBuffers(u),p=new Me(d.vertex,3);p.name=s||i.attrName,p.applyMatrix4(n),e.morphAttributes.position.push(p)}parseNormals(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.Normals.a;let s=[];return i==="IndexToDirect"&&("NormalIndex"in e?s=e.NormalIndex.a:"NormalsIndex"in e&&(s=e.NormalsIndex.a)),{dataSize:3,buffer:n,indices:s,mappingType:t,referenceType:i}}parseUVs(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.UV.a;let s=[];return i==="IndexToDirect"&&(s=e.UVIndex.a),{dataSize:2,buffer:n,indices:s,mappingType:t,referenceType:i}}parseVertexColors(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.Colors.a;let s=[];i==="IndexToDirect"&&(s=e.ColorIndex.a);for(let a=0,o=new se;a<n.length;a+=4)o.fromArray(n,a).convertSRGBToLinear().toArray(n,a);return{dataSize:4,buffer:n,indices:s,mappingType:t,referenceType:i}}parseMaterialIndices(e){const t=e.MappingInformationType,i=e.ReferenceInformationType;if(t==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:i};const n=e.Materials.a,s=[];for(let a=0;a<n.length;++a)s.push(a);return{dataSize:1,buffer:n,indices:s,mappingType:t,referenceType:i}}parseNurbsGeometry(e){const t=parseInt(e.Order);if(isNaN(t))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",e.Order,e.id),new $e;const i=t-1,n=e.KnotVector.a,s=[],a=e.Points.a;for(let u=0,d=a.length;u<d;u+=4)s.push(new rt().fromArray(a,u));let o,l;if(e.Form==="Closed")s.push(s[0]);else if(e.Form==="Periodic"){o=i,l=n.length-1-o;for(let u=0;u<i;++u)s.push(s[u])}const h=new gz(i,n,s,o,l).getPoints(s.length*12);return new $e().setFromPoints(h)}}class vz{parse(){const e=[],t=this.parseClips();if(t!==void 0)for(const i in t){const n=t[i],s=this.addClip(n);e.push(s)}return e}parseClips(){if(It.Objects.AnimationCurve===void 0)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=It.Objects.AnimationCurveNode,t=new Map;for(const i in e){const n=e[i];if(n.attrName.match(/S|R|T|DeformPercent/)!==null){const s={id:n.id,attr:n.attrName,curves:{}};t.set(s.id,s)}}return t}parseAnimationCurves(e){const t=It.Objects.AnimationCurve;for(const i in t){const n={id:t[i].id,times:t[i].KeyTime.a.map(xz),values:t[i].KeyValueFloat.a},s=Xi.get(n.id);if(s!==void 0){const a=s.parents[0].ID,o=s.parents[0].relationship;o.match(/X/)?e.get(a).curves.x=n:o.match(/Y/)?e.get(a).curves.y=n:o.match(/Z/)?e.get(a).curves.z=n:o.match(/DeformPercent/)&&e.has(a)&&(e.get(a).curves.morph=n)}}}parseAnimationLayers(e){const t=It.Objects.AnimationLayer,i=new Map;for(const n in t){const s=[],a=Xi.get(parseInt(n));a!==void 0&&(a.children.forEach(function(l,c){if(e.has(l.ID)){const h=e.get(l.ID);if(h.curves.x!==void 0||h.curves.y!==void 0||h.curves.z!==void 0){if(s[c]===void 0){const u=Xi.get(l.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(u!==void 0){const d=It.Objects.Model[u.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const p={modelName:d.attrName?Ct.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};Jn.traverse(function(m){m.ID===d.id&&(p.transform=m.matrix,m.userData.transformData&&(p.eulerOrder=m.userData.transformData.eulerOrder))}),p.transform||(p.transform=new pe),"PreRotation"in d&&(p.preRotation=d.PreRotation.value),"PostRotation"in d&&(p.postRotation=d.PostRotation.value),s[c]=p}}s[c]&&(s[c][h.attr]=h)}else if(h.curves.morph!==void 0){if(s[c]===void 0){const u=Xi.get(l.ID).parents.filter(function(y){return y.relationship!==void 0})[0].ID,d=Xi.get(u).parents[0].ID,p=Xi.get(d).parents[0].ID,m=Xi.get(p).parents[0].ID,A=It.Objects.Model[m],g={modelName:A.attrName?Ct.sanitizeNodeName(A.attrName):"",morphName:It.Objects.Deformer[u].attrName};s[c]=g}s[c][h.attr]=h}}}),i.set(parseInt(n),s))}return i}parseAnimStacks(e){const t=It.Objects.AnimationStack,i={};for(const n in t){const s=Xi.get(parseInt(n)).children;s.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const a=e.get(s[0].ID);i[n]={name:t[n].attrName,layer:a}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(n){t=t.concat(i.generateTracks(n))}),new eo(e.name,-1,t)}generateTracks(e){const t=[];let i=new x,n=new x;if(e.transform&&e.transform.decompose(i,new Qe,n),i=i.toArray(),n=n.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const s=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");s!==void 0&&t.push(s)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const s=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);s!==void 0&&t.push(s)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const s=this.generateVectorTrack(e.modelName,e.S.curves,n,"scale");s!==void 0&&t.push(s)}if(e.DeformPercent!==void 0){const s=this.generateMorphTrack(e);s!==void 0&&t.push(s)}return t}generateVectorTrack(e,t,i,n){const s=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(s,t,i);return new Za(e+"."+n,s,a)}generateRotationTrack(e,t,i,n,s){let a,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const u=this.interpolateRotations(t.x,t.y,t.z,s);a=u[0],o=u[1]}i!==void 0&&(i=i.map(Ut.degToRad),i.push(s),i=new Tt().fromArray(i),i=new Qe().setFromEuler(i)),n!==void 0&&(n=n.map(Ut.degToRad),n.push(s),n=new Tt().fromArray(n),n=new Qe().setFromEuler(n).invert());const l=new Qe,c=new Tt,h=[];if(!o||!a)return new Ir(e+".quaternion",[0],[0]);for(let u=0;u<o.length;u+=3)c.set(o[u],o[u+1],o[u+2],s),l.setFromEuler(c),i!==void 0&&l.premultiply(i),n!==void 0&&l.multiply(n),u>2&&new Qe().fromArray(h,(u-3)/3*4).dot(l)<0&&l.set(-l.x,-l.y,-l.z,-l.w),l.toArray(h,u/3*4);return new Ir(e+".quaternion",a,h)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(s){return s/100}),n=Jn.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new Ja(e.modelName+".morphTargetInfluences["+n+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,n){return i-n}),t.length>1){let i=1,n=t[0];for(let s=1;s<t.length;s++){const a=t[s];a!==n&&(t[i]=a,n=a,i++)}t=t.slice(0,i)}return t}getKeyframeTrackValues(e,t,i){const n=i,s=[];let a=-1,o=-1,l=-1;return e.forEach(function(c){if(t.x&&(a=t.x.times.indexOf(c)),t.y&&(o=t.y.times.indexOf(c)),t.z&&(l=t.z.times.indexOf(c)),a!==-1){const h=t.x.values[a];s.push(h),n[0]=h}else s.push(n[0]);if(o!==-1){const h=t.y.values[o];s.push(h),n[1]=h}else s.push(n[1]);if(l!==-1){const h=t.z.values[l];s.push(h),n[2]=h}else s.push(n[2])}),s}interpolateRotations(e,t,i,n){const s=[],a=[];s.push(e.times[0]),a.push(Ut.degToRad(e.values[0])),a.push(Ut.degToRad(t.values[0])),a.push(Ut.degToRad(i.values[0]));for(let o=1;o<e.values.length;o++){const l=[e.values[o-1],t.values[o-1],i.values[o-1]];if(isNaN(l[0])||isNaN(l[1])||isNaN(l[2]))continue;const c=l.map(Ut.degToRad),h=[e.values[o],t.values[o],i.values[o]];if(isNaN(h[0])||isNaN(h[1])||isNaN(h[2]))continue;const u=h.map(Ut.degToRad),d=[h[0]-l[0],h[1]-l[1],h[2]-l[2]],p=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(p[0]>=180||p[1]>=180||p[2]>=180){const A=Math.max(...p)/180,g=new Tt(...c,n),y=new Tt(...u,n),_=new Qe().setFromEuler(g),v=new Qe().setFromEuler(y);_.dot(v)&&v.set(-v.x,-v.y,-v.z,-v.w);const b=e.times[o-1],T=e.times[o]-b,E=new Qe,M=new Tt;for(let S=0;S<1;S+=1/A)E.copy(_.clone().slerp(v.clone(),S)),s.push(b+S*T),M.setFromQuaternion(E,n),a.push(M.x),a.push(M.y),a.push(M.z)}else s.push(e.times[o]),a.push(Ut.degToRad(e.values[o])),a.push(Ut.degToRad(t.values[o])),a.push(Ut.degToRad(i.values[o]))}return[s,a]}}class _z{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new s1,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(n,s){const a=n.match(/^[\s\t]*;/),o=n.match(/^[\s\t]*$/);if(a||o)return;const l=n.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=n.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),h=n.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(n,l):c?t.parseNodeProperty(n,c,i[++s]):h?t.popStack():n.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(n)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),n=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),s={name:i},a=this.parseNodeAttr(n),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,s):i in o?(i==="PoseNode"?o.PoseNode.push(s):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),a.id!==""&&(o[i][a.id]=s)):typeof a.id=="number"?(o[i]={},o[i][a.id]=s):i!=="Properties70"&&(i==="PoseNode"?o[i]=[s]:o[i]=s),typeof a.id=="number"&&(s.id=a.id),a.name!==""&&(s.attrName=a.name),a.type!==""&&(s.attrType=a.type),this.pushStack(s)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",n="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),n=e[2]),{id:t,name:i,type:n}}parseNodeProperty(e,t,i){let n=t[1].replace(/^"/,"").replace(/"$/,"").trim(),s=t[2].replace(/^"/,"").replace(/"$/,"").trim();n==="Content"&&s===","&&(s=i.replace(/"/g,"").replace(/,$/,"").trim());const a=this.getCurrentNode();if(a.name==="Properties70"){this.parseNodeSpecialProperty(e,n,s);return}if(n==="C"){const l=s.split(",").slice(1),c=parseInt(l[0]),h=parseInt(l[1]);let u=s.split(",").slice(3);u=u.map(function(d){return d.trim().replace(/^"/,"")}),n="connections",s=[c,h],Ez(s,u),a[n]===void 0&&(a[n]=[])}n==="Node"&&(a.id=s),n in a&&Array.isArray(a[n])?a[n].push(s):n!=="a"?a[n]=s:a.a=s,this.setCurrentProp(a,n),n==="a"&&s.slice(-1)!==","&&(a.a=K0(s))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=K0(t.a))}parseNodeSpecialProperty(e,t,i){const n=i.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),s=n[0],a=n[1],o=n[2],l=n[3];let c=n[4];switch(a){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=K0(c);break}this.getPrevNode()[s]={type:a,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),s)}}class bz{parse(e){const t=new n1(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const n=new s1;for(;!this.endOfContent(t);){const s=this.parseNode(t,i);s!==null&&n.add(s.name,s)}return n}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},n=t>=7500?e.getUint64():e.getUint32(),s=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const a=e.getUint8(),o=e.getString(a);if(n===0)return null;const l=[];for(let d=0;d<s;d++)l.push(this.parseProperty(e));const c=l.length>0?l[0]:"",h=l.length>1?l[1]:"",u=l.length>2?l[2]:"";for(i.singleProperty=s===1&&e.getOffset()===n;n>e.getOffset();){const d=this.parseNode(e,t);d!==null&&this.parseSubNode(o,i,d)}return i.propertyList=l,typeof c=="number"&&(i.id=c),h!==""&&(i.attrName=h),u!==""&&(i.attrType=u),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const n=i.propertyList[0];Array.isArray(n)?(t[i.name]=i,i.a=n):t[i.name]=n}else if(e==="Connections"&&i.name==="C"){const n=[];i.propertyList.forEach(function(s,a){a!==0&&n.push(s)}),t.connections===void 0&&(t.connections=[]),t.connections.push(n)}else if(i.name==="Properties70")Object.keys(i).forEach(function(s){t[s]=i[s]});else if(e==="Properties70"&&i.name==="P"){let n=i.propertyList[0],s=i.propertyList[1];const a=i.propertyList[2],o=i.propertyList[3];let l;n.indexOf("Lcl ")===0&&(n=n.replace("Lcl ","Lcl_")),s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),s==="Color"||s==="ColorRGB"||s==="Vector"||s==="Vector3D"||s.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[n]={type:s,type2:a,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const n=e.getUint32(),s=e.getUint32(),a=e.getUint32();if(s===0)switch(t){case"b":case"c":return e.getBooleanArray(n);case"d":return e.getFloat64Array(n);case"f":return e.getFloat32Array(n);case"i":return e.getInt32Array(n);case"l":return e.getInt64Array(n)}const o=Ea(new Uint8Array(e.getArrayBuffer(a))),l=new n1(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(n);case"d":return l.getFloat64Array(n);case"f":return l.getFloat32Array(n);case"i":return l.getInt32Array(n);case"l":return l.getInt64Array(n)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class n1{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i<e;i++)t.push(this.getBoolean());return t}getUint8(){const e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){const e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){const e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getInt32());return t}getUint32(){const e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){const e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getFloat32());return t}getFloat64(){const e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getFloat64());return t}getArrayBuffer(e){const t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){const t=this.offset;let i=new Uint8Array(this.dv.buffer,t,e);this.skip(e);const n=i.indexOf(0);return n>=0&&(i=new Uint8Array(this.dv.buffer,t,n)),this._textDecoder.decode(i)}}class s1{add(e,t){this[e]=t}}function wz(r){const e="Kaydara FBX Binary  \0";return r.byteLength>=e.length&&e===l1(r,0,e.length)}function Cz(r){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(n){const s=r[n-1];return r=r.slice(t+n),t++,s}for(let n=0;n<e.length;++n)if(i(1)===e[n])return!1;return!0}function r1(r){const e=/FBXVersion: (\d+)/,t=r.match(e);if(t)return parseInt(t[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function xz(r){return r/46186158e3}const Sz=[];function dg(r,e,t,i){let n;switch(i.mappingType){case"ByPolygonVertex":n=r;break;case"ByPolygon":n=e;break;case"ByVertice":n=t;break;case"AllSame":n=i.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+i.mappingType)}i.referenceType==="IndexToDirect"&&(n=i.indices[n]);const s=n*i.dataSize,a=s+i.dataSize;return Mz(Sz,i.buffer,s,a)}const $0=new Tt,bh=new x;function a1(r){const e=new pe,t=new pe,i=new pe,n=new pe,s=new pe,a=new pe,o=new pe,l=new pe,c=new pe,h=new pe,u=new pe,d=new pe,p=r.inheritType?r.inheritType:0;if(r.translation&&e.setPosition(bh.fromArray(r.translation)),r.preRotation){const C=r.preRotation.map(Ut.degToRad);C.push(r.eulerOrder||Tt.DEFAULT_ORDER),t.makeRotationFromEuler($0.fromArray(C))}if(r.rotation){const C=r.rotation.map(Ut.degToRad);C.push(r.eulerOrder||Tt.DEFAULT_ORDER),i.makeRotationFromEuler($0.fromArray(C))}if(r.postRotation){const C=r.postRotation.map(Ut.degToRad);C.push(r.eulerOrder||Tt.DEFAULT_ORDER),n.makeRotationFromEuler($0.fromArray(C)),n.invert()}r.scale&&s.scale(bh.fromArray(r.scale)),r.scalingOffset&&o.setPosition(bh.fromArray(r.scalingOffset)),r.scalingPivot&&a.setPosition(bh.fromArray(r.scalingPivot)),r.rotationOffset&&l.setPosition(bh.fromArray(r.rotationOffset)),r.rotationPivot&&c.setPosition(bh.fromArray(r.rotationPivot)),r.parentMatrixWorld&&(u.copy(r.parentMatrix),h.copy(r.parentMatrixWorld));const m=t.clone().multiply(i).multiply(n),A=new pe;A.extractRotation(h);const g=new pe;g.copyPosition(h);const y=g.clone().invert().multiply(h),_=A.clone().invert().multiply(y),v=s,b=new pe;if(p===0)b.copy(A).multiply(m).multiply(_).multiply(v);else if(p===1)b.copy(A).multiply(_).multiply(m).multiply(v);else{const D=new pe().scale(new x().setFromMatrixScale(u)).clone().invert(),O=_.clone().multiply(D);b.copy(A).multiply(m).multiply(O).multiply(v)}const T=c.clone().invert(),E=a.clone().invert();let M=e.clone().multiply(l).multiply(c).multiply(t).multiply(i).multiply(n).multiply(T).multiply(o).multiply(a).multiply(s).multiply(E);const S=new pe().copyPosition(M),w=h.clone().multiply(S);return d.copyPosition(w),M=d.clone().multiply(b),M.premultiply(h.invert()),M}function o1(r){r=r||0;const e=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return r===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),e[0]):e[r]}function K0(r){return r.split(",").map(function(t){return parseFloat(t)})}function l1(r,e,t){return e===void 0&&(e=0),t===void 0&&(t=r.byteLength),new TextDecoder().decode(new Uint8Array(r,e,t))}function Ez(r,e){for(let t=0,i=r.length,n=e.length;t<n;t++,i++)r[i]=e[t]}function Mz(r,e,t,i){for(let n=t,s=0;n<i;n++,s++)r[s]=e[n];return r}class c1 extends i1{async loadAsync(e,t){const i=Rt.DEFAULT_IMAGE;Rt.DEFAULT_IMAGE||(Rt.DEFAULT_IMAGE=mm);const n=await super.loadAsync(e,t);return Rt.DEFAULT_IMAGE=i,n}}class h1 extends Zt{load(e,t,i,n){return this.setResponseType("arraybuffer"),super.load(e,s=>{const a=Y0(new Uint8Array(s)),o=new Map(Object.entries(a).map(([l,c])=>[l,new File([c],l)]));t?.(o)},i,n)}}const Tz=["hdr","exr","webp","avif","ktx","hdrpng","svg","cube","ico","bmp","gif","tiff"],Dn=class Dn extends xt{constructor(e){super(e),this.isGLTFLoader2=!0,this._resPathUrlModifier={oldResourcePath:"",newResourcePath:"",modify:t=>{if(!Dn._UseResourcePath||!this._resPathUrlModifier.oldResourcePath||!this._resPathUrlModifier.newResourcePath)return t;let i=this._resPathUrlModifier.oldResourcePath;const n=this._resPathUrlModifier.newResourcePath;return i?.startsWith("/")&&/^https?:\/\//i.test(n)&&(i=n.replace(/(^https?:\/\/[^/]+).*/i,"$1")+i),t.startsWith(i)?t.replace(i,n):t}},this.preparsers=[],this.gltfViewerParser=t=>i=>{this._resPathUrlModifier.newResourcePath=i.options.path,this._resPathUrlModifier.oldResourcePath=i.json?.extras?.resourcePath,t.assetManager.importer.addURLModifier(this._resPathUrlModifier.modify),i.importOptions=this.importOptions||void 0;const n=i.getDependency;i.getDependency=async(d,p)=>{const m=await n.call(i,d,p);return u1(m,i.bundledResources),m};const s=i.createUniqueName;i.createUniqueName=d=>{const p=(i.importOptions?.createUniqueNames??Dn.CreateUniqueNames)==="auto";let m=!1;return p?m=!i.json?.scenes[i.json.scene??0]?.extras?.rootSceneModelRoot:m=i.importOptions?.createUniqueNames===!0||Dn.CreateUniqueNames===!0&&i.importOptions?.createUniqueNames!==!1,m?s.call(i,d):d};const a=Ui()+".drc",o=Ui()+".ktx2",l=i.json?.extensionsRequired?.includes?.("KHR_draco_mesh_compression");if(l){const d=t.assetManager.importer.registerFile(a);d&&this.setDRACOLoader(d)}i.json?.extensionsUsed?.includes?.("EXT_meshopt_compression")&&(window.MeshoptDecoder?(this.setMeshoptDecoder(window.MeshoptDecoder),i.options.meshoptDecoder=window.MeshoptDecoder):console.error("Add GLTFMeshOptDecodePlugin(and initialize it) to viewer to enable EXT_meshopt_compression decode"));const h=t.assetManager.importer.registerFile(o);h&&(this.setKTX2Loader(h),i.options.ktx2Loader=h);const u=Tz.map(d=>Ui()+"."+d);return u.forEach(d=>t.assetManager.importer.registerFile(d)),{name:"GLTF2_HELPER_PLUGIN",beforeRoot:async()=>{const d=i.json.extras?.[Dn.BundledResourcesKey];!d||d.__isLoadedResources||(i.bundledResources=await fo.ImportResources(d,i,t))},afterRoot:async d=>{d._bundledResources=i.bundledResources,await fo.ImportViewerConfig(i,t,d.scenes||[d.scene]),l&&t.assetManager.importer.unregisterFile(a),h&&t.assetManager.importer.unregisterFile(o),u.forEach(p=>t.assetManager.importer.unregisterFile(p)),t.assetManager.importer.removeURLModifier(this._resPathUrlModifier.modify)}}},this.preparsers.push(fT),xt.ObjectConstructors.DirectionalLight=Qm,xt.ObjectConstructors.PointLight=jm,xt.ObjectConstructors.SpotLight=Wm,xt.ObjectConstructors.MeshStandardMaterial=ai,xt.ObjectConstructors.MeshBasicMaterial=ys,xt.ObjectConstructors.MeshPhysicalMaterial=ai,xt.ObjectConstructors.LineBasicMaterial=$n,xt.ObjectConstructors.PerspectiveCamera=PM,xt.ObjectConstructors.OrthographicCamera=DM}async preparse(e,t){for(const i of this.preparsers)e=await i.process(e,t);return e}parse(e,t,i,n,s){this.preparse.call(this,e,s||t).then(a=>{if(!a||!a.byteLength&&typeof a!="string"){Dn.AllowEmptyFiles?i&&i({scene:new Ri,scenes:[],animations:[],cameras:[]}):n&&n(new ErrorEvent("GLTFLoader2: empty file"));return}const o=Rt.DEFAULT_IMAGE;Rt.DEFAULT_IMAGE||(Rt.DEFAULT_IMAGE=mm);const l=this.importOptions?.useMeshLines??Dn.UseMeshLines;return xt.ObjectConstructors.LineBasicMaterial=l?ji:$n,a?super.parse(a,t,c=>{Rt.DEFAULT_IMAGE=o,xt.ObjectConstructors.LineBasicMaterial=l?ji:$n;for(const h of c.scenes)h.updateMatrixWorld();i&&i(c)},n):n&&n(new ErrorEvent("no data"))}).catch(a=>{console.error(a),n&&n(a??new ErrorEvent("unknown error"))})}transform(e,t){let i=e?e.scene||!!e.scenes&&e.scenes.length>0&&e.scenes[0]:void 0;if(!i)return;i&&i.children.length===1&&!i.userData?.rootSceneModelRoot&&!i.importedViewerConfig&&i.name==="AuxScene"&&!e.cameras?.length&&(i=i.children[0],i.removeFromParent()),i.userData||(i.userData={}),e.userData&&(i.userData.gltfExtras=e.userData),e.cameras&&e.cameras.forEach(l=>!l.parent&&i.add(l)),e.asset&&(i.userData.gltfAsset=e.asset),t.importAsModelRoot?i.userData.rootSceneModelRoot=!0:t.importAsModelRoot===!1&&i.userData.rootSceneModelRoot&&delete i.userData.rootSceneModelRoot;const n=[],s=new Map,a=new Set;if(i.traverse(l=>{l.userData.gltfUUID&&(an(l,"uuid",l.userData.gltfUUID,!0,!0),delete l.userData.gltfUUID),l.isLine&&n.push(l),l.uuid&&(s.has(l.uuid)||s.set(l.uuid,[]),s.get(l.uuid).push(l)),l.name&&(s.has(l.name)||s.set(l.name,[]),s.get(l.name).push(l));const c=l;c.geometry&&c.geometry.isBufferGeometry&&(c.geometry.userData.isPlaceholder?c.geometry=Bs.DummyGeometry:a.add(c.geometry));const h=Array.isArray(c.material)?c.material:c.material?[c.material]:[];for(let u=0;u<h.length;u++){const d=h[u];d?.userData.isPlaceholder&&(d.isLineBasicMaterial?h[u]=Bs.DummyLineBasicMaterial:d.isLineMaterial?h[u]=Bs.DummyLineMaterial:h[u]=Bs.DummyMaterial)}Array.isArray(c.material)&&c.material.length?c.material=h:h.length===1&&(c.material=h[0])}),a.forEach(l=>{u1(l,e._bundledResources)}),e.animations.length>0){i.animations=[];for(const l of e.animations){let c=!1;if(l.userData.rootRefs){for(const h of l.userData.rootRefs){const u=s.get(h)||[];for(const d of u)d.animations||(d.animations=[]),d.animations.includes(l)||d.animations.push(l),c=!0}c&&delete l.userData.rootRefs}c||i.animations.push(l)}}if(this.importOptions?.useMeshLines??Dn.UseMeshLines)for(const l of n)Iz(l);return i.importedBundledResources=e._bundledResources,i}register(e){return super.register(e)}setup(e,t){this.register(Md.Import(e.loadConfigResources));for(const i of t)this.register(i);for(const i of Dn.ImportExtensions)this.register(i);return this.register(this.gltfViewerParser(e)),this}};Dn._EmbedResourcePath=!1,Dn._UseResourcePath=!0,Dn.ImportExtensions=[Td.Import,Ed.Import,rh.Import,Cl.Import,xl.Import,wl.Import,e=>({name:"_EMBED_RESOURCE_PATH",afterRoot:async t=>{!Dn._EmbedResourcePath||!t.scene||(t.userData.resourcePath=e.options.path)}})],Dn.UseMeshLines=!0,Dn.CreateUniqueNames="auto",Dn.BundledResourcesKey="BundledResources",Dn.AllowEmptyFiles=!0;let Ml=Dn;function Iz(r){const e=r.parent;if(!e){console.warn("GLTFLoader2: Line has no parent",r);return}r.geometry.index&&(r.geometry=r.geometry.toNonIndexed());const t=r.isLineSegments?new LM(new UM,r.material):new u0(new d0,r.material);let i=r.geometry.attributes.position.array;if(r.isLineLoop){const h=new Float32Array(i.length+3);h.set(i),h.set(i.subarray(0,3),i.length),i=h}t.geometry.setPositions(i);const n=r.geometry.attributes.color?.array;n&&t.geometry.setColors&&t.geometry.setColors(n),t.geometry.name=r.geometry.name,an(t.geometry,"uuid",r.geometry.uuid,!0,!0),t.geometry.userData={...r.geometry.userData};const s=e.children.indexOf(r);e.add(t);const{geometry:a,material:o}=t,l=r.userData;r.userData={},r.userData.__keepShadowDef||(r.castShadow=t.castShadow,r.receiveShadow=t.receiveShadow),t.copy(r,!1),t.geometry=a,t.material=o,[...r.children].map(h=>{t.add(h)}),t.userData={...t.userData,...l},an(t,"uuid",r.uuid,!0,!0),r.removeFromParent(),t.computeLineDistances();const c=e.children.indexOf(t);c>=0&&c!==s&&(e.children.splice(c,1),e.children.splice(s,0,t))}function u1(r,e){if(r&&r.userData){const t=r.userData.gltfExtensions;delete r.userData.gltfExtensions,r.userData=ke.Deserialize(r.userData,{},e),r.userData.gltfExtensions=t}}const J0=new WeakMap;class d1 extends li{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,n){const s=new Zt(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,a=>{this.parse(a,t,n)},i,n)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,vt).catch(i)}decodeDracoFile(e,t,i,n,s=Dt,a=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:n||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:s};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const i=JSON.stringify(t);if(J0.has(e)){const l=J0.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let n;const s=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(s,a).then(l=>(n=l,new Promise((c,h)=>{n._callbacks[s]={resolve:c,reject:h},n.postMessage({type:"decode",id:s,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{n&&s&&this._releaseTask(n,s)}),J0.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new $e;e.index&&t.setIndex(new Xe(e.index.array,1));for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i],s=n.name,a=n.array,o=n.itemSize,l=new Xe(a,o);s==="color"&&(this._assignVertexColorSpace(l,n.vertexColorSpace),l.normalized=!(a instanceof Float32Array)),t.setAttribute(s,l)}return t}_assignVertexColorSpace(e,t){if(t!==vt)return;const i=new se;for(let n=0,s=e.count;n<s;n++)i.fromBufferAttribute(e,n).convertSRGBToLinear(),e.setXYZ(n,i.r,i.g,i.b)}_loadLibrary(e,t){const i=new Zt(this.manager);return i.setPath(this.decoderPath),i.setResponseType(t),i.setWithCredentials(this.withCredentials),new Promise((n,s)=>{i.load(e,n,void 0,s)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const n=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const s=Pz,a=["/* draco decoder */",n,"","/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const n=new Worker(this.workerSourceURL);n._callbacks={},n._taskCosts={},n._taskLoad=0,n.postMessage({type:"init",decoderConfig:this.decoderConfig}),n.onmessage=function(s){const a=s.data;switch(a.type){case"decode":n._callbacks[a.id].resolve(a);break;case"error":n._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.type+'"')}},this.workerPool.push(n)}else this.workerPool.sort(function(n,s){return n._taskLoad>s._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}const Pz=`
function DRACOWorker() {

	let decoderConfig;
	let decoderPending;

	onmessage = function ( e ) {

		const message = e.data;

		switch ( message.type ) {

			case 'init':
				decoderConfig = message.decoderConfig;
				decoderPending = new Promise( function ( resolve/*, reject*/ ) {

					decoderConfig.onModuleLoaded = function ( draco ) {

						// Module is Promise-like. Wrap before resolving to avoid loop.
						resolve( { draco: draco } );

					};

					DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef

				} );
				break;

			case 'decode':
				const buffer = message.buffer;
				const taskConfig = message.taskConfig;
				decoderPending.then( ( module ) => {

					const draco = module.draco;
					const decoder = new draco.Decoder();

					try {

						const geometry = decodeGeometry( draco, decoder, new Int8Array( buffer ), taskConfig );

						const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );

						if ( geometry.index ) buffers.push( geometry.index.array.buffer );

						self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );

					} catch ( error ) {

						console.error( error );

						self.postMessage( { type: 'error', id: message.id, error: error.message } );

					} finally {

						draco.destroy( decoder );

					}

				} );
				break;

		}

	};

	function decodeGeometry( draco, decoder, array, taskConfig ) {

		const attributeIDs = taskConfig.attributeIDs;
		const attributeTypes = taskConfig.attributeTypes;

		let dracoGeometry;
		let decodingStatus;

		const geometryType = decoder.GetEncodedGeometryType( array );

		if ( geometryType === draco.TRIANGULAR_MESH ) {

			dracoGeometry = new draco.Mesh();
			decodingStatus = decoder.DecodeArrayToMesh( array, array.byteLength, dracoGeometry );

		} else if ( geometryType === draco.POINT_CLOUD ) {

			dracoGeometry = new draco.PointCloud();
			decodingStatus = decoder.DecodeArrayToPointCloud( array, array.byteLength, dracoGeometry );

		} else {

			throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );

		}

		if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {

			throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );

		}

		const geometry = { index: null, attributes: [] };

		// Gather all vertex attributes.
		for ( const attributeName in attributeIDs ) {

			const attributeType = self[ attributeTypes[ attributeName ] ];

			let attribute;
			let attributeID;

			// A Draco file may be created with default vertex attributes, whose attribute IDs
			// are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
			// a Draco file may contain a custom set of attributes, identified by known unique
			// IDs. glTF files always do the latter, and .drc files typically do the former.
			if ( taskConfig.useUniqueIDs ) {

				attributeID = attributeIDs[ attributeName ];
				attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );

			} else {

				attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );

				if ( attributeID === - 1 ) continue;

				attribute = decoder.GetAttribute( dracoGeometry, attributeID );

			}

			const attributeResult = decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute );

			if ( attributeName === 'color' ) {

				attributeResult.vertexColorSpace = taskConfig.vertexColorSpace;

			}

			geometry.attributes.push( attributeResult );

		}

		// Add index.
		if ( geometryType === draco.TRIANGULAR_MESH ) {

			geometry.index = decodeIndex( draco, decoder, dracoGeometry );

		}

		draco.destroy( dracoGeometry );

		return geometry;

	}

	function decodeIndex( draco, decoder, dracoGeometry ) {

		const numFaces = dracoGeometry.num_faces();
		const numIndices = numFaces * 3;
		const byteLength = numIndices * 4;

		const ptr = draco._malloc( byteLength );
		decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
		const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
		draco._free( ptr );

		return { array: index, itemSize: 1 };

	}

	function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {

		const numComponents = attribute.num_components();
		const numPoints = dracoGeometry.num_points();
		const numValues = numPoints * numComponents;
		const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
		const dataType = getDracoDataType( draco, attributeType );

		const ptr = draco._malloc( byteLength );
		decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
		const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
		draco._free( ptr );

		return {
			name: attributeName,
			array: array,
			itemSize: numComponents
		};

	}

	function getDracoDataType( draco, attributeType ) {

		switch ( attributeType ) {

			case Float32Array: return draco.DT_FLOAT32;
			case Int8Array: return draco.DT_INT8;
			case Int16Array: return draco.DT_INT16;
			case Int32Array: return draco.DT_INT32;
			case Uint8Array: return draco.DT_UINT8;
			case Uint16Array: return draco.DT_UINT16;
			case Uint32Array: return draco.DT_UINT32;

		}

	}

}
`,So=class So extends d1{constructor(e){super(e),this.encoderPending=null,this.encoderConfig={type:"js"},this.isDRACOLoader2=!0,this.setDecoderPath(So.DRACO_LIBRARY_PATH),this.setDecoderConfig({type:"js"})}transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new ye(e,new ai({color:new se(1,1,1)})):void 0}preload(e=!0,t=!1){return e&&super.preload(),t&&this.initEncoder(),this}async initEncoder(){if(this.encoderPending)return this.encoderPending;const e=typeof WebAssembly!="object"||this.encoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_encoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_encoder.wasm","arraybuffer"))),this.encoderPending=Promise.all(t).then(i=>{const n=i[0];return e||(this.encoderConfig.wasmBinary=i[1]),(0,eval)(n+`
DracoEncoderModule;`)?.()}),this.encoderPending}async initDecoder(){await this._initDecoder();const e=await fetch(this.workerSourceURL).then(async i=>i.text()).then(i=>{const n=i.indexOf("/* worker */");if(n<1)throw new Error("unable to load decoder module");return i.substring(0,n-1)});return(0,eval)(e+`
DracoDecoderModule;`)?.()}async _loadLibrary(e,t){return So.LibraryValueMap[e]?So.LibraryValueMap[e]:So.LibraryValueMap[e]=await super._loadLibrary(e,t)}static SetDecoderJsString(e){this.LibraryValueMap["draco_decoder.js"]=e}};So.DRACO_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/google/draco@1.5.6/javascript/",So.LibraryValueMap={};let fg=So;class Z0 extends Iy{constructor(e){super(e),this.type=$t}parse(e){const w=Math.pow(2.7182818,2.2);function C(R,L){let Q=0;for(let U=0;U<65536;++U)(U==0||R[U>>3]&1<<(U&7))&&(L[Q++]=U);const P=Q-1;for(;Q<65536;)L[Q++]=0;return P}function D(R){for(let L=0;L<16384;L++)R[L]={},R[L].len=0,R[L].lit=0,R[L].p=null}const O={l:0,c:0,lc:0};function F(R,L,Q,P,U){for(;Q<R;)L=L<<8|Qt(P,U),Q+=8;Q-=R,O.l=L>>Q&(1<<R)-1,O.c=L,O.lc=Q}const G=new Array(59);function j(R){for(let Q=0;Q<=58;++Q)G[Q]=0;for(let Q=0;Q<65537;++Q)G[R[Q]]+=1;let L=0;for(let Q=58;Q>0;--Q){const P=L+G[Q]>>1;G[Q]=L,L=P}for(let Q=0;Q<65537;++Q){const P=R[Q];P>0&&(R[Q]=P|G[P]++<<6)}}function W(R,L,Q,P,U,k){const V=L;let H=0,ee=0;for(;P<=U;P++){if(V.value-L.value>Q)return!1;F(6,H,ee,R,V);const ne=O.l;if(H=O.c,ee=O.lc,k[P]=ne,ne==63){if(V.value-L.value>Q)throw new Error("Something wrong with hufUnpackEncTable");F(8,H,ee,R,V);let Z=O.l+6;if(H=O.c,ee=O.lc,P+Z>U+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Z--;)k[P++]=0;P--}else if(ne>=59){let Z=ne-59+2;if(P+Z>U+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Z--;)k[P++]=0;P--}}j(k)}function K(R){return R&63}function q(R){return R>>6}function oe(R,L,Q,P){for(;L<=Q;L++){const U=q(R[L]),k=K(R[L]);if(U>>k)throw new Error("Invalid table entry");if(k>14){const V=P[U>>k-14];if(V.len)throw new Error("Invalid table entry");if(V.lit++,V.p){const H=V.p;V.p=new Array(V.lit);for(let ee=0;ee<V.lit-1;++ee)V.p[ee]=H[ee]}else V.p=new Array(1);V.p[V.lit-1]=L}else if(k){let V=0;for(let H=1<<14-k;H>0;H--){const ee=P[(U<<14-k)+V];if(ee.len||ee.p)throw new Error("Invalid table entry");ee.len=k,ee.lit=L,V++}}}return!0}const re={c:0,lc:0};function Ce(R,L,Q,P){R=R<<8|Qt(Q,P),L+=8,re.c=R,re.lc=L}const Ie={c:0,lc:0};function Ue(R,L,Q,P,U,k,V,H,ee){if(R==L){P<8&&(Ce(Q,P,U,k),Q=re.c,P=re.lc),P-=8;let ne=Q>>P;if(ne=new Uint8Array([ne])[0],H.value+ne>ee)return!1;const Z=V[H.value-1];for(;ne-- >0;)V[H.value++]=Z}else if(H.value<ee)V[H.value++]=R;else return!1;Ie.c=Q,Ie.lc=P}function te(R){return R&65535}function ce(R){const L=te(R);return L>32767?L-65536:L}const me={a:0,b:0};function we(R,L){const Q=ce(R),U=ce(L),k=Q+(U&1)+(U>>1),V=k,H=k-U;me.a=V,me.b=H}function je(R,L){const Q=te(R),P=te(L),U=Q-(P>>1)&65535,k=P+U-32768&65535;me.a=k,me.b=U}function ht(R,L,Q,P,U,k,V){const H=V<16384,ee=Q>U?U:Q;let ne=1,Z,ge;for(;ne<=ee;)ne<<=1;for(ne>>=1,Z=ne,ne>>=1;ne>=1;){ge=0;const Ae=ge+k*(U-Z),xe=k*ne,Te=k*Z,Le=P*ne,He=P*Z;let nt,ni,_t,ut;for(;ge<=Ae;ge+=Te){let hi=ge;const et=ge+P*(Q-Z);for(;hi<=et;hi+=He){const yi=hi+Le,ds=hi+xe,Pi=ds+Le;H?(we(R[hi+L],R[ds+L]),nt=me.a,_t=me.b,we(R[yi+L],R[Pi+L]),ni=me.a,ut=me.b,we(nt,ni),R[hi+L]=me.a,R[yi+L]=me.b,we(_t,ut),R[ds+L]=me.a,R[Pi+L]=me.b):(je(R[hi+L],R[ds+L]),nt=me.a,_t=me.b,je(R[yi+L],R[Pi+L]),ni=me.a,ut=me.b,je(nt,ni),R[hi+L]=me.a,R[yi+L]=me.b,je(_t,ut),R[ds+L]=me.a,R[Pi+L]=me.b)}if(Q&ne){const yi=hi+xe;H?we(R[hi+L],R[yi+L]):je(R[hi+L],R[yi+L]),nt=me.a,R[yi+L]=me.b,R[hi+L]=nt}}if(U&ne){let hi=ge;const et=ge+P*(Q-Z);for(;hi<=et;hi+=He){const yi=hi+Le;H?we(R[hi+L],R[yi+L]):je(R[hi+L],R[yi+L]),nt=me.a,R[yi+L]=me.b,R[hi+L]=nt}}Z=ne,ne>>=1}return ge}function Ze(R,L,Q,P,U,k,V,H,ee){let ne=0,Z=0;const ge=V,Ae=Math.trunc(P.value+(U+7)/8);for(;P.value<Ae;)for(Ce(ne,Z,Q,P),ne=re.c,Z=re.lc;Z>=14;){const Te=ne>>Z-14&16383,Le=L[Te];if(Le.len)Z-=Le.len,Ue(Le.lit,k,ne,Z,Q,P,H,ee,ge),ne=Ie.c,Z=Ie.lc;else{if(!Le.p)throw new Error("hufDecode issues");let He;for(He=0;He<Le.lit;He++){const nt=K(R[Le.p[He]]);for(;Z<nt&&P.value<Ae;)Ce(ne,Z,Q,P),ne=re.c,Z=re.lc;if(Z>=nt&&q(R[Le.p[He]])==(ne>>Z-nt&(1<<nt)-1)){Z-=nt,Ue(Le.p[He],k,ne,Z,Q,P,H,ee,ge),ne=Ie.c,Z=Ie.lc;break}}if(He==Le.lit)throw new Error("hufDecode issues")}}const xe=8-U&7;for(ne>>=xe,Z-=xe;Z>0;){const Te=L[ne<<14-Z&16383];if(Te.len)Z-=Te.len,Ue(Te.lit,k,ne,Z,Q,P,H,ee,ge),ne=Ie.c,Z=Ie.lc;else throw new Error("hufDecode issues")}return!0}function Y(R,L,Q,P,U,k){const V={value:0},H=Q.value,ee=Mt(L,Q),ne=Mt(L,Q);Q.value+=4;const Z=Mt(L,Q);if(Q.value+=4,ee<0||ee>=65537||ne<0||ne>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const ge=new Array(65537),Ae=new Array(16384);D(Ae);const xe=P-(Q.value-H);if(W(R,Q,xe,ee,ne,ge),Z>8*(P-(Q.value-H)))throw new Error("Something wrong with hufUncompress");oe(ge,ee,ne,Ae),Ze(ge,Ae,R,Q,Z,ne,k,U,V)}function fe(R,L,Q){for(let P=0;P<Q;++P)L[P]=R[L[P]]}function he(R){for(let L=1;L<R.length;L++){const Q=R[L-1]+R[L]-128;R[L]=Q}}function Se(R,L){let Q=0,P=Math.floor((R.length+1)/2),U=0;const k=R.length-1;for(;!(U>k||(L[U++]=R[Q++],U>k));)L[U++]=R[P++]}function Ee(R){let L=R.byteLength;const Q=new Array;let P=0;const U=new DataView(R);for(;L>0;){const k=U.getInt8(P++);if(k<0){const V=-k;L-=V+1;for(let H=0;H<V;H++)Q.push(U.getUint8(P++))}else{const V=k;L-=2;const H=U.getUint8(P++);for(let ee=0;ee<V+1;ee++)Q.push(H)}}return Q}function De(R,L,Q,P,U,k){let V=new DataView(k.buffer);const H=Q[R.idx[0]].width,ee=Q[R.idx[0]].height,ne=3,Z=Math.floor(H/8),ge=Math.ceil(H/8),Ae=Math.ceil(ee/8),xe=H-(ge-1)*8,Te=ee-(Ae-1)*8,Le={value:0},He=new Array(ne),nt=new Array(ne),ni=new Array(ne),_t=new Array(ne),ut=new Array(ne);for(let et=0;et<ne;++et)ut[et]=L[R.idx[et]],He[et]=et<1?0:He[et-1]+ge*Ae,nt[et]=new Float32Array(64),ni[et]=new Uint16Array(64),_t[et]=new Uint16Array(ge*64);for(let et=0;et<Ae;++et){let yi=8;et==Ae-1&&(yi=Te);let ds=8;for(let Jt=0;Jt<ge;++Jt){Jt==ge-1&&(ds=xe);for(let bt=0;bt<ne;++bt)ni[bt].fill(0),ni[bt][0]=U[He[bt]++],N(Le,P,ni[bt]),B(ni[bt],nt[bt]),J(nt[bt]);le(nt);for(let bt=0;bt<ne;++bt)ue(nt[bt],_t[bt],Jt*64)}let Pi=0;for(let Jt=0;Jt<ne;++Jt){const bt=Q[R.idx[Jt]].type;for(let xn=8*et;xn<8*et+yi;++xn){Pi=ut[Jt][xn];for(let Fa=0;Fa<Z;++Fa){const Ns=Fa*64+(xn&7)*8;V.setUint16(Pi+0*bt,_t[Jt][Ns+0],!0),V.setUint16(Pi+2*bt,_t[Jt][Ns+1],!0),V.setUint16(Pi+4*bt,_t[Jt][Ns+2],!0),V.setUint16(Pi+6*bt,_t[Jt][Ns+3],!0),V.setUint16(Pi+8*bt,_t[Jt][Ns+4],!0),V.setUint16(Pi+10*bt,_t[Jt][Ns+5],!0),V.setUint16(Pi+12*bt,_t[Jt][Ns+6],!0),V.setUint16(Pi+14*bt,_t[Jt][Ns+7],!0),Pi+=16*bt}}if(Z!=ge)for(let xn=8*et;xn<8*et+yi;++xn){const Fa=ut[Jt][xn]+8*Z*2*bt,Ns=Z*64+(xn&7)*8;for(let Sn=0;Sn<ds;++Sn)V.setUint16(Fa+Sn*2*bt,_t[Jt][Ns+Sn],!0)}}}const hi=new Uint16Array(H);V=new DataView(k.buffer);for(let et=0;et<ne;++et){Q[R.idx[et]].decoded=!0;const yi=Q[R.idx[et]].type;if(Q[et].type==2)for(let ds=0;ds<ee;++ds){const Pi=ut[et][ds];for(let Jt=0;Jt<H;++Jt)hi[Jt]=V.getUint16(Pi+Jt*2*yi,!0);for(let Jt=0;Jt<H;++Jt)V.setFloat32(Pi+Jt*2*yi,X(hi[Jt]),!0)}}}function N(R,L,Q){let P,U=1;for(;U<64;)P=L[R.value],P==65280?U=64:P>>8==255?U+=P&255:(Q[U]=P,U++),R.value++}function B(R,L){L[0]=X(R[0]),L[1]=X(R[1]),L[2]=X(R[5]),L[3]=X(R[6]),L[4]=X(R[14]),L[5]=X(R[15]),L[6]=X(R[27]),L[7]=X(R[28]),L[8]=X(R[2]),L[9]=X(R[4]),L[10]=X(R[7]),L[11]=X(R[13]),L[12]=X(R[16]),L[13]=X(R[26]),L[14]=X(R[29]),L[15]=X(R[42]),L[16]=X(R[3]),L[17]=X(R[8]),L[18]=X(R[12]),L[19]=X(R[17]),L[20]=X(R[25]),L[21]=X(R[30]),L[22]=X(R[41]),L[23]=X(R[43]),L[24]=X(R[9]),L[25]=X(R[11]),L[26]=X(R[18]),L[27]=X(R[24]),L[28]=X(R[31]),L[29]=X(R[40]),L[30]=X(R[44]),L[31]=X(R[53]),L[32]=X(R[10]),L[33]=X(R[19]),L[34]=X(R[23]),L[35]=X(R[32]),L[36]=X(R[39]),L[37]=X(R[45]),L[38]=X(R[52]),L[39]=X(R[54]),L[40]=X(R[20]),L[41]=X(R[22]),L[42]=X(R[33]),L[43]=X(R[38]),L[44]=X(R[46]),L[45]=X(R[51]),L[46]=X(R[55]),L[47]=X(R[60]),L[48]=X(R[21]),L[49]=X(R[34]),L[50]=X(R[37]),L[51]=X(R[47]),L[52]=X(R[50]),L[53]=X(R[56]),L[54]=X(R[59]),L[55]=X(R[61]),L[56]=X(R[35]),L[57]=X(R[36]),L[58]=X(R[48]),L[59]=X(R[49]),L[60]=X(R[57]),L[61]=X(R[58]),L[62]=X(R[62]),L[63]=X(R[63])}function J(R){const L=.5*Math.cos(.7853975),Q=.5*Math.cos(3.14159/16),P=.5*Math.cos(3.14159/8),U=.5*Math.cos(3*3.14159/16),k=.5*Math.cos(5*3.14159/16),V=.5*Math.cos(3*3.14159/8),H=.5*Math.cos(7*3.14159/16),ee=new Array(4),ne=new Array(4),Z=new Array(4),ge=new Array(4);for(let Ae=0;Ae<8;++Ae){const xe=Ae*8;ee[0]=P*R[xe+2],ee[1]=V*R[xe+2],ee[2]=P*R[xe+6],ee[3]=V*R[xe+6],ne[0]=Q*R[xe+1]+U*R[xe+3]+k*R[xe+5]+H*R[xe+7],ne[1]=U*R[xe+1]-H*R[xe+3]-Q*R[xe+5]-k*R[xe+7],ne[2]=k*R[xe+1]-Q*R[xe+3]+H*R[xe+5]+U*R[xe+7],ne[3]=H*R[xe+1]-k*R[xe+3]+U*R[xe+5]-Q*R[xe+7],Z[0]=L*(R[xe+0]+R[xe+4]),Z[3]=L*(R[xe+0]-R[xe+4]),Z[1]=ee[0]+ee[3],Z[2]=ee[1]-ee[2],ge[0]=Z[0]+Z[1],ge[1]=Z[3]+Z[2],ge[2]=Z[3]-Z[2],ge[3]=Z[0]-Z[1],R[xe+0]=ge[0]+ne[0],R[xe+1]=ge[1]+ne[1],R[xe+2]=ge[2]+ne[2],R[xe+3]=ge[3]+ne[3],R[xe+4]=ge[3]-ne[3],R[xe+5]=ge[2]-ne[2],R[xe+6]=ge[1]-ne[1],R[xe+7]=ge[0]-ne[0]}for(let Ae=0;Ae<8;++Ae)ee[0]=P*R[16+Ae],ee[1]=V*R[16+Ae],ee[2]=P*R[48+Ae],ee[3]=V*R[48+Ae],ne[0]=Q*R[8+Ae]+U*R[24+Ae]+k*R[40+Ae]+H*R[56+Ae],ne[1]=U*R[8+Ae]-H*R[24+Ae]-Q*R[40+Ae]-k*R[56+Ae],ne[2]=k*R[8+Ae]-Q*R[24+Ae]+H*R[40+Ae]+U*R[56+Ae],ne[3]=H*R[8+Ae]-k*R[24+Ae]+U*R[40+Ae]-Q*R[56+Ae],Z[0]=L*(R[Ae]+R[32+Ae]),Z[3]=L*(R[Ae]-R[32+Ae]),Z[1]=ee[0]+ee[3],Z[2]=ee[1]-ee[2],ge[0]=Z[0]+Z[1],ge[1]=Z[3]+Z[2],ge[2]=Z[3]-Z[2],ge[3]=Z[0]-Z[1],R[0+Ae]=ge[0]+ne[0],R[8+Ae]=ge[1]+ne[1],R[16+Ae]=ge[2]+ne[2],R[24+Ae]=ge[3]+ne[3],R[32+Ae]=ge[3]-ne[3],R[40+Ae]=ge[2]-ne[2],R[48+Ae]=ge[1]-ne[1],R[56+Ae]=ge[0]-ne[0]}function le(R){for(let L=0;L<64;++L){const Q=R[0][L],P=R[1][L],U=R[2][L];R[0][L]=Q+1.5747*U,R[1][L]=Q-.1873*P-.4682*U,R[2][L]=Q+1.8556*P}}function ue(R,L,Q){for(let P=0;P<64;++P)L[Q+P]=Hn.toHalfFloat(ve(R[P]))}function ve(R){return R<=1?Math.sign(R)*Math.pow(Math.abs(R),2.2):Math.sign(R)*Math.pow(w,Math.abs(R)-1)}function Ke(R){return new DataView(R.array.buffer,R.offset.value,R.size)}function be(R){const L=R.viewer.buffer.slice(R.offset.value,R.offset.value+R.size),Q=new Uint8Array(Ee(L)),P=new Uint8Array(Q.length);return he(Q),Se(Q,P),new DataView(P.buffer)}function Ye(R){const L=R.array.slice(R.offset.value,R.offset.value+R.size),Q=Ea(L),P=new Uint8Array(Q.length);return he(Q),Se(Q,P),new DataView(P.buffer)}function at(R){const L=R.viewer,Q={value:R.offset.value},P=new Uint16Array(R.width*R.scanlineBlockSize*(R.channels*R.type)),U=new Uint8Array(8192);let k=0;const V=new Array(R.channels);for(let Te=0;Te<R.channels;Te++)V[Te]={},V[Te].start=k,V[Te].end=V[Te].start,V[Te].nx=R.width,V[Te].ny=R.lines,V[Te].size=R.type,k+=V[Te].nx*V[Te].ny*V[Te].size;const H=Pe(L,Q),ee=Pe(L,Q);if(ee>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(H<=ee)for(let Te=0;Te<ee-H+1;Te++)U[Te+H]=Nt(L,Q);const ne=new Uint16Array(65536),Z=C(U,ne),ge=Mt(L,Q);Y(R.array,L,Q,ge,P,k);for(let Te=0;Te<R.channels;++Te){const Le=V[Te];for(let He=0;He<V[Te].size;++He)ht(P,Le.start+He,Le.nx,Le.size,Le.ny,Le.nx*Le.size,Z)}fe(ne,P,k);let Ae=0;const xe=new Uint8Array(P.buffer.byteLength);for(let Te=0;Te<R.lines;Te++)for(let Le=0;Le<R.channels;Le++){const He=V[Le],nt=He.nx*He.size,ni=new Uint8Array(P.buffer,He.end*2,nt*2);xe.set(ni,Ae),Ae+=nt*2,He.end+=nt}return new DataView(xe.buffer)}function Be(R){const L=R.array.slice(R.offset.value,R.offset.value+R.size),Q=Ea(L),P=R.lines*R.channels*R.width,U=R.type==1?new Uint16Array(P):new Uint32Array(P);let k=0,V=0;const H=new Array(4);for(let ee=0;ee<R.lines;ee++)for(let ne=0;ne<R.channels;ne++){let Z=0;switch(R.type){case 1:H[0]=k,H[1]=H[0]+R.width,k=H[1]+R.width;for(let ge=0;ge<R.width;++ge){const Ae=Q[H[0]++]<<8|Q[H[1]++];Z+=Ae,U[V]=Z,V++}break;case 2:H[0]=k,H[1]=H[0]+R.width,H[2]=H[1]+R.width,k=H[2]+R.width;for(let ge=0;ge<R.width;++ge){const Ae=Q[H[0]++]<<24|Q[H[1]++]<<16|Q[H[2]++]<<8;Z+=Ae,U[V]=Z,V++}break}}return new DataView(U.buffer)}function Ne(R){const L=R.viewer,Q={value:R.offset.value},P=new Uint8Array(R.width*R.lines*(R.channels*R.type*2)),U={version:ze(L,Q),unknownUncompressedSize:ze(L,Q),unknownCompressedSize:ze(L,Q),acCompressedSize:ze(L,Q),dcCompressedSize:ze(L,Q),rleCompressedSize:ze(L,Q),rleUncompressedSize:ze(L,Q),rleRawSize:ze(L,Q),totalAcUncompressedCount:ze(L,Q),totalDcUncompressedCount:ze(L,Q),acCompression:ze(L,Q)};if(U.version<2)throw new Error("EXRLoader.parse: "+ts.compression+" version "+U.version+" is unsupported");const k=new Array;let V=Pe(L,Q)-2;for(;V>0;){const Le=dt(L.buffer,Q),He=Nt(L,Q),nt=He>>2&3,ni=(He>>4)-1,_t=new Int8Array([ni])[0],ut=Nt(L,Q);k.push({name:Le,index:_t,type:ut,compression:nt}),V-=Le.length+3}const H=ts.channels,ee=new Array(R.channels);for(let Le=0;Le<R.channels;++Le){const He=ee[Le]={},nt=H[Le];He.name=nt.name,He.compression=0,He.decoded=!1,He.type=nt.pixelType,He.pLinear=nt.pLinear,He.width=R.width,He.height=R.lines}const ne={idx:new Array(3)};for(let Le=0;Le<R.channels;++Le){const He=ee[Le];for(let nt=0;nt<k.length;++nt){const ni=k[nt];He.name==ni.name&&(He.compression=ni.compression,ni.index>=0&&(ne.idx[ni.index]=Le),He.offset=Le)}}let Z,ge,Ae;if(U.acCompressedSize>0)switch(U.acCompression){case 0:Z=new Uint16Array(U.totalAcUncompressedCount),Y(R.array,L,Q,U.acCompressedSize,Z,U.totalAcUncompressedCount);break;case 1:const Le=R.array.slice(Q.value,Q.value+U.totalAcUncompressedCount),He=Ea(Le);Z=new Uint16Array(He.buffer),Q.value+=U.totalAcUncompressedCount;break}if(U.dcCompressedSize>0){const Le={array:R.array,offset:Q,size:U.dcCompressedSize};ge=new Uint16Array(Ye(Le).buffer),Q.value+=U.dcCompressedSize}if(U.rleRawSize>0){const Le=R.array.slice(Q.value,Q.value+U.rleCompressedSize),He=Ea(Le);Ae=Ee(He.buffer),Q.value+=U.rleCompressedSize}let xe=0;const Te=new Array(ee.length);for(let Le=0;Le<Te.length;++Le)Te[Le]=new Array;for(let Le=0;Le<R.lines;++Le)for(let He=0;He<ee.length;++He)Te[He].push(xe),xe+=ee[He].width*R.type*2;De(ne,Te,ee,Z,ge,P);for(let Le=0;Le<ee.length;++Le){const He=ee[Le];if(!He.decoded)switch(He.compression){case 2:let nt=0,ni=0;for(let _t=0;_t<R.lines;++_t){let ut=Te[Le][nt];for(let hi=0;hi<He.width;++hi){for(let et=0;et<2*He.type;++et)P[ut++]=Ae[ni+et*He.width*He.height];ni++}nt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(P.buffer)}function dt(R,L){const Q=new Uint8Array(R);let P=0;for(;Q[L.value+P]!=0;)P+=1;const U=new TextDecoder().decode(Q.slice(L.value,L.value+P));return L.value=L.value+P+1,U}function We(R,L,Q){const P=new TextDecoder().decode(new Uint8Array(R).slice(L.value,L.value+Q));return L.value=L.value+Q,P}function qe(R,L){const Q=yt(R,L),P=Mt(R,L);return[Q,P]}function Ft(R,L){const Q=Mt(R,L),P=Mt(R,L);return[Q,P]}function yt(R,L){const Q=R.getInt32(L.value,!0);return L.value=L.value+4,Q}function Mt(R,L){const Q=R.getUint32(L.value,!0);return L.value=L.value+4,Q}function Qt(R,L){const Q=R[L.value];return L.value=L.value+1,Q}function Nt(R,L){const Q=R.getUint8(L.value);return L.value=L.value+1,Q}const ze=function(R,L){let Q;return"getBigInt64"in DataView.prototype?Q=Number(R.getBigInt64(L.value,!0)):Q=R.getUint32(L.value+4,!0)+Number(R.getUint32(L.value,!0)<<32),L.value+=8,Q};function I(R,L){const Q=R.getFloat32(L.value,!0);return L.value+=4,Q}function ie(R,L){return Hn.toHalfFloat(I(R,L))}function X(R){const L=(R&31744)>>10,Q=R&1023;return(R>>15?-1:1)*(L?L===31?Q?NaN:1/0:Math.pow(2,L-15)*(1+Q/1024):6103515625e-14*(Q/1024))}function Pe(R,L){const Q=R.getUint16(L.value,!0);return L.value+=2,Q}function Ve(R,L){return X(Pe(R,L))}function jt(R,L,Q,P){const U=Q.value,k=[];for(;Q.value<U+P-1;){const V=dt(L,Q),H=yt(R,Q),ee=Nt(R,Q);Q.value+=3;const ne=yt(R,Q),Z=yt(R,Q);k.push({name:V,pixelType:H,pLinear:ee,xSampling:ne,ySampling:Z})}return Q.value+=1,k}function Ot(R,L){const Q=I(R,L),P=I(R,L),U=I(R,L),k=I(R,L),V=I(R,L),H=I(R,L),ee=I(R,L),ne=I(R,L);return{redX:Q,redY:P,greenX:U,greenY:k,blueX:V,blueY:H,whiteX:ee,whiteY:ne}}function Si(R,L){const Q=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],P=Nt(R,L);return Q[P]}function hn(R,L){const Q=yt(R,L),P=yt(R,L),U=yt(R,L),k=yt(R,L);return{xMin:Q,yMin:P,xMax:U,yMax:k}}function ii(R,L){const Q=["INCREASING_Y","DECREASING_Y"],P=Nt(R,L);return Q[P]}function es(R,L){const Q=I(R,L),P=I(R,L);return[Q,P]}function Ji(R,L){const Q=I(R,L),P=I(R,L),U=I(R,L);return[Q,P,U]}function wn(R,L,Q,P,U){if(P==="string"||P==="stringvector"||P==="iccProfile")return We(L,Q,U);if(P==="chlist")return jt(R,L,Q,U);if(P==="chromaticities")return Ot(R,Q);if(P==="compression")return Si(R,Q);if(P==="box2i")return hn(R,Q);if(P==="lineOrder")return ii(R,Q);if(P==="float")return I(R,Q);if(P==="v2f")return es(R,Q);if(P==="v3f")return Ji(R,Q);if(P==="int")return yt(R,Q);if(P==="rational")return qe(R,Q);if(P==="timecode")return Ft(R,Q);if(P==="preview")return Q.value+=U,"skipped";Q.value+=U}function To(R,L,Q){const P={};if(R.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");P.version=R.getUint8(4);const U=R.getUint8(5);P.spec={singleTile:!!(U&2),longName:!!(U&4),deepFormat:!!(U&8),multiPart:!!(U&16)},Q.value=8;let k=!0;for(;k;){const V=dt(L,Q);if(V==0)k=!1;else{const H=dt(L,Q),ee=Mt(R,Q),ne=wn(R,L,Q,H,ee);ne===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${H}'.`):P[V]=ne}}if((U&-5)!=0)throw console.error("THREE.EXRHeader:",P),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return P}function Xr(R,L,Q,P,U){const k={size:0,viewer:L,array:Q,offset:P,width:R.dataWindow.xMax-R.dataWindow.xMin+1,height:R.dataWindow.yMax-R.dataWindow.yMin+1,channels:R.channels.length,channelLineOffsets:{},scanOrder:null,bytesPerLine:null,lines:null,inputSize:null,type:null,uncompress:null,getter:null,format:null,colorSpace:Dt};switch(R.compression){case"NO_COMPRESSION":k.lines=1,k.uncompress=Ke;break;case"RLE_COMPRESSION":k.lines=1,k.uncompress=be;break;case"ZIPS_COMPRESSION":k.lines=1,k.uncompress=Ye;break;case"ZIP_COMPRESSION":k.lines=16,k.uncompress=Ye;break;case"PIZ_COMPRESSION":k.lines=32,k.uncompress=at;break;case"PXR24_COMPRESSION":k.lines=16,k.uncompress=Be;break;case"DWAA_COMPRESSION":k.lines=32,k.uncompress=Ne;break;case"DWAB_COMPRESSION":k.lines=256,k.uncompress=Ne;break;default:throw new Error("EXRLoader.parse: "+R.compression+" is unsupported")}k.scanlineBlockSize=k.lines;const V={};for(const Z of R.channels)switch(Z.name){case"Y":case"R":case"G":case"B":case"A":V[Z.name]=!0,k.type=Z.pixelType}let H=!1;if(V.R&&V.G&&V.B)H=!V.A,k.outputChannels=4,k.decodeChannels={R:0,G:1,B:2,A:3};else if(V.Y)k.outputChannels=1,k.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(k.type==1)switch(U){case zt:k.getter=Ve,k.inputSize=2;break;case $t:k.getter=Pe,k.inputSize=2;break}else if(k.type==2)switch(U){case zt:k.getter=I,k.inputSize=4;break;case $t:k.getter=ie,k.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+k.type+" for "+R.compression+".");k.blockCount=k.height/k.scanlineBlockSize;for(let Z=0;Z<k.blockCount;Z++)ze(L,P);const ee=k.width*k.height*k.outputChannels;switch(U){case zt:k.byteArray=new Float32Array(ee),H&&k.byteArray.fill(1,0,ee);break;case $t:k.byteArray=new Uint16Array(ee),H&&k.byteArray.fill(15360,0,ee);break;default:console.error("THREE.EXRLoader: unsupported type: ",U);break}let ne=0;for(const Z of R.channels)k.decodeChannels[Z.name]!==void 0&&(k.channelLineOffsets[Z.name]=ne*k.width),ne+=Z.pixelType*2;return k.bytesPerLine=k.width*ne,k.outLineWidth=k.width*k.outputChannels,R.lineOrder==="INCREASING_Y"?k.scanOrder=Z=>Z:k.scanOrder=Z=>k.height-1-Z,k.outputChannels==4?(k.format=Kt,k.colorSpace=Dt):(k.format=ka,k.colorSpace=si),k}const Ua=new DataView(e),Cn=new Uint8Array(e),Cs={value:0},ts=To(Ua,e,Cs),Pt=Xr(ts,Ua,Cn,Cs,this.type),nf={value:0};for(let R=0;R<Pt.height/Pt.scanlineBlockSize;R++){const L=yt(Ua,Cs)-ts.dataWindow.yMin;Pt.size=Mt(Ua,Cs),Pt.lines=L+Pt.scanlineBlockSize>Pt.height?Pt.height-L:Pt.scanlineBlockSize;const P=Pt.size<Pt.lines*Pt.bytesPerLine?Pt.uncompress(Pt):Ke(Pt);Cs.value+=Pt.size;for(let U=0;U<Pt.scanlineBlockSize;U++){const k=R*Pt.scanlineBlockSize,V=U+Pt.scanOrder(k);if(V>=Pt.height)continue;const H=U*Pt.bytesPerLine,ee=(Pt.height-1-V)*Pt.outLineWidth;for(let ne=0;ne<Pt.channels;ne++){const Z=ts.channels[ne].name,ge=Pt.channelLineOffsets[Z],Ae=Pt.decodeChannels[Z];if(Ae!==void 0){nf.value=H+ge;for(let xe=0;xe<Pt.width;xe++){const Te=ee+xe*Pt.outputChannels+Ae;Pt.byteArray[Te]=Pt.getter(P,nf)}}}}}return{header:ts,width:Pt.width,height:Pt.height,data:Pt.byteArray,format:Pt.format,colorSpace:Pt.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,i,n){function s(a,o){a.colorSpace=o.colorSpace,a.minFilter=st,a.magFilter=st,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,o)}return super.load(e,s,i,n)}}const e_=new WeakMap;class f1 extends li{constructor(e){super(e),this.libraryPath="",this.libraryPending=null,this.libraryBinary=null,this.libraryConfig={},this.url="",this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.workerConfig={},this.materials=[],this.warnings=[]}setLibraryPath(e){return this.libraryPath=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,n){const s=new Zt(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),this.url=e,s.load(e,a=>{if(e_.has(a))return e_.get(a).promise.then(t).catch(n);this.decodeObjects(a,e).then(o=>{o.userData.warnings=this.warnings,this.warnings=[],t(o)}).catch(o=>n(o))},i,n)}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}decodeObjects(e,t){let i,n;const s=e.byteLength,a=this._getWorker(s).then(o=>(i=o,n=this.workerNextTaskID++,new Promise((l,c)=>{i._callbacks[n]={resolve:l,reject:c},i.postMessage({type:"decode",id:n,buffer:e},[e])}))).then(o=>this._createGeometry(o.data)).catch(o=>{throw o});return a.catch(()=>!0).then(()=>{i&&n&&this._releaseTask(i,n)}),e_.set(e,{url:t,promise:a}),a}parse(e,t,i){this.decodeObjects(e,"").then(n=>{n.userData.warnings=this.warnings,t(n)}).catch(n=>i(n))}_compareMaterials(e){if(this.materials.includes(e))return e;const t={};t.name=e.name,t.color={},t.color.r=e.color.r,t.color.g=e.color.g,t.color.b=e.color.b,t.type=e.type,t.vertexColors=e.vertexColors;const i=JSON.stringify(t);for(let n=0;n<this.materials.length;n++){const s=this.materials[n],a={};if(a.name=s.name,a.color={},a.color.r=s.color.r,a.color.g=s.color.g,a.color.b=s.color.b,a.type=s.type,a.vertexColors=s.vertexColors,JSON.stringify(a)===i)return s}return this.materials.push(e),e}_createMaterial(e,t){if(e===void 0)return new Ka({color:new se(1,1,1),metalness:.8,name:li.DEFAULT_MATERIAL_NAME,side:Zi});const i=new Nc({color:new se(e.diffuseColor.r/255,e.diffuseColor.g/255,e.diffuseColor.b/255),emissive:new se(e.emissionColor.r,e.emissionColor.g,e.emissionColor.b),flatShading:e.disableLighting,ior:e.indexOfRefraction,name:e.name,reflectivity:e.reflectivity,opacity:1-e.transparency,side:Zi,specularColor:e.specularColor,transparent:e.transparency>0});if(i.userData.id=e.id,e.pbrSupported){const s=e.pbr;i.anisotropy=s.anisotropic,i.anisotropyRotation=s.anisotropicRotation,i.color=new se(s.baseColor.r,s.baseColor.g,s.baseColor.b),i.clearcoat=s.clearcoat,i.clearcoatRoughness=s.clearcoatRoughness,i.metalness=s.metallic,i.transmission=1-s.opacity,i.roughness=s.roughness,i.sheen=s.sheen,i.specularIntensity=s.specular,i.thickness=s.subsurface}e.pbrSupported&&e.pbr.opacity===0&&e.transparency===1&&(i.opacity=.2,i.transmission=1);const n=new to;for(let s=0;s<e.textures.length;s++){const a=e.textures[s];if(a.image!==null){const o=n.load(a.image);switch(a.type){case"Bump":i.bumpMap=o;break;case"Diffuse":i.map=o;break;case"Emap":i.envMap=o;break;case"Opacity":i.transmissionMap=o;break;case"Transparency":i.alphaMap=o,i.transparent=!0;break;case"PBR_Alpha":i.alphaMap=o,i.transparent=!0;break;case"PBR_AmbientOcclusion":i.aoMap=o;break;case"PBR_Anisotropic":i.anisotropyMap=o;break;case"PBR_BaseColor":i.map=o;break;case"PBR_Clearcoat":i.clearcoatMap=o;break;case"PBR_ClearcoatBump":i.clearcoatNormalMap=o;break;case"PBR_ClearcoatRoughness":i.clearcoatRoughnessMap=o;break;case"PBR_Displacement":i.displacementMap=o;break;case"PBR_Emission":i.emissiveMap=o;break;case"PBR_Metallic":i.metalnessMap=o;break;case"PBR_Roughness":i.roughnessMap=o;break;case"PBR_Sheen":i.sheenColorMap=o;break;case"PBR_Specular":i.specularColorMap=o;break;case"PBR_Subsurface":i.thicknessMap=o;break;default:this.warnings.push({message:`THREE.3DMLoader: No conversion exists for 3dm ${a.type}.`,type:"no conversion"});break}o.wrapS=a.wrapU===0?Bn:ui,o.wrapT=a.wrapV===0?Bn:ui,a.repeat&&o.repeat.set(a.repeat[0],a.repeat[1])}}return t&&new Z0().load(t.image,function(s){s.mapping=THREE.EquirectangularReflectionMapping,i.envMap=s}),i}_createGeometry(e){const t=new ft,i=[],n=[],s=[];t.userData.layers=e.layers,t.userData.groups=e.groups,t.userData.settings=e.settings,t.userData.settings.renderSettings=e.renderSettings,t.userData.strings=e.strings,t.userData.objectType="File3dm",t.userData.materials=null,t.name=this.url;let a=e.objects;const o=e.materials;for(let l=0;l<a.length;l++){const c=a[l],h=c.attributes;switch(c.objectType){case"InstanceDefinition":n.push(c);break;case"InstanceReference":s.push(c);break;default:let u=null;switch(h.materialSource.name){case"ObjectMaterialSource_MaterialFromLayer":h.layerIndex>=0&&(u=e.layers[h.layerIndex].renderMaterialIndex);break;case"ObjectMaterialSource_MaterialFromObject":h.materialIndex>=0&&(u=h.materialIndex);break}let d=null;if(u>=0){const A=o[u];d=this._createMaterial(A,e.renderEnvironment)}const p=this._createObject(c,d);if(p===void 0)continue;const m=e.layers[h.layerIndex];p.visible=m?m.visible:!0,h.isInstanceDefinitionObject?i.push(p):t.add(p);break}}for(let l=0;l<n.length;l++){const c=n[l];a=[];for(let h=0;h<c.attributes.objectIds.length;h++){const u=c.attributes.objectIds[h];for(let d=0;d<i.length;d++){const p=i[d].userData.attributes.id;u===p&&a.push(i[d])}}for(let h=0;h<s.length;h++){const u=s[h];if(u.geometry.parentIdefId===c.attributes.id){const d=u.geometry.xform.array,p=new pe;if(p.set(...d),a.length===1){const m=a[0].clone(!0);if(m.name=u.attributes.name||m.name,m.applyMatrix4(p),u.attributes.materialIndex>=0&&u.attributes.materialIndex!==a[0].userData.attributes.materialIndex){const A=o[u.attributes.materialIndex],g=this._createMaterial(A);m.material=this._compareMaterials(g)}if(m.userData.defAttributes=m.userData.attributes,m.userData.defObjectType=m.userData.objectType,m.userData.attributes={...m.userData.attributes,...u.attributes},m.userData.objectType=u.objectType,u.attributes.layerIndex!==void 0){const A=e.layers[u.attributes.layerIndex];m.visible=A?A.visible:m.visible}t.add(m)}else{console.warn("THREE.Rhino3dmLoader: InstanceReference with multiple/no objects, not all properties will be copied.");const m=new ft;m.applyMatrix4(p);for(let A=0;A<a.length;A++)m.add(a[A].clone(!0));t.add(m)}}}}return t.userData.materials=this.materials,t.name="",t}_createObject(e,t){const i=new Ly,n=e.attributes;let s,a,o,l;switch(e.objectType){case"Point":case"PointSet":s=i.parse(e.geometry),s.attributes.hasOwnProperty("color")?a=new Tr({vertexColors:!0,sizeAttenuation:!1,size:2}):(o=n.drawColor,l=new se(o.r/255,o.g/255,o.b/255),a=new Tr({color:l,sizeAttenuation:!1,size:2})),a=this._compareMaterials(a);const c=new jo(s,a);return c.userData.attributes=n,c.userData.objectType=e.objectType,n.name&&(c.name=n.name),c;case"Mesh":case"Extrusion":case"SubD":case"Brep":if(e.geometry===null)return;s=i.parse(e.geometry),t===null&&(t=this._createMaterial()),s.attributes.hasOwnProperty("color")&&(t.vertexColors=!0),t=this._compareMaterials(t);const h=new ye(s,t);return h.castShadow=n.castsShadows,h.receiveShadow=n.receivesShadows,h.userData.attributes=n,h.userData.objectType=e.objectType,n.name&&(h.name=n.name,s.name=n.name),h;case"Curve":s=i.parse(e.geometry),o=n.drawColor,l=new se(o.r/255,o.g/255,o.b/255),a=new Ei({color:l}),a=this._compareMaterials(a);const u=new fn(s,a);return u.userData.attributes=n,u.userData.objectType=e.objectType,n.name&&(u.name=n.name),u;case"TextDot":s=e.geometry;const d=document.createElement("canvas").getContext("2d"),p=`${s.fontHeight}px ${s.fontFace}`;d.font=p;const m=d.measureText(s.text).width+10,A=s.fontHeight+10,g=window.devicePixelRatio;d.canvas.width=m*g,d.canvas.height=A*g,d.canvas.style.width=m+"px",d.canvas.style.height=A+"px",d.setTransform(g,0,0,g,0,0),d.font=p,d.textBaseline="middle",d.textAlign="center",l=n.drawColor,d.fillStyle=`rgba(${l.r},${l.g},${l.b},${l.a})`,d.fillRect(0,0,m,A),d.fillStyle="white",d.fillText(s.text,m/2,A/2);const y=new Wo(d.canvas);y.minFilter=st,y.generateMipmaps=!1,y.wrapS=ui,y.wrapT=ui,a=new du({map:y,depthTest:!1});const _=new Zf(a);return _.position.set(s.point[0],s.point[1],s.point[2]),_.scale.set(m/10,A/10,1),_.userData.attributes=n,_.userData.objectType=e.objectType,n.name&&(_.name=n.name),_;case"Light":s=e.geometry;let v;switch(s.lightStyle.name){case"LightStyle_WorldPoint":v=new tl,v.castShadow=n.castsShadows,v.position.set(s.location[0],s.location[1],s.location[2]),v.shadow.normalBias=.1;break;case"LightStyle_WorldSpot":v=new zc,v.castShadow=n.castsShadows,v.position.set(s.location[0],s.location[1],s.location[2]),v.target.position.set(s.direction[0],s.direction[1],s.direction[2]),v.angle=s.spotAngleRadians,v.shadow.normalBias=.1;break;case"LightStyle_WorldRectangular":v=new Bp;const b=Math.abs(s.width[2]),T=Math.abs(s.length[0]);v.position.set(s.location[0]-T/2,s.location[1],s.location[2]-b/2),v.height=T,v.width=b,v.lookAt(s.direction[0],s.direction[1],s.direction[2]);break;case"LightStyle_WorldDirectional":v=new il,v.castShadow=n.castsShadows,v.position.set(s.location[0],s.location[1],s.location[2]),v.target.position.set(s.direction[0],s.direction[1],s.direction[2]),v.shadow.normalBias=.1;break}return v&&(v.intensity=s.intensity,o=s.diffuse,l=new se(o.r/255,o.g/255,o.b/255),v.color=l,v.userData.attributes=n,v.userData.objectType=e.objectType),v}}_initLibrary(){if(!this.libraryPending){const e=new Zt(this.manager);e.setPath(this.libraryPath);const t=new Promise((s,a)=>{e.load("rhino3dm.js",s,void 0,a)}),i=new Zt(this.manager);i.setPath(this.libraryPath),i.setResponseType("arraybuffer");const n=new Promise((s,a)=>{i.load("rhino3dm.wasm",s,void 0,a)});this.libraryPending=Promise.all([t,n]).then(([s,a])=>{this.libraryConfig.wasmBinary=a;const o=Dz,l=["/* rhino3dm.js */",s,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([l]))})}return this.libraryPending}_getWorker(e){return this._initLibrary().then(()=>{if(this.workerPool.length<this.workerLimit){const i=new Worker(this.workerSourceURL);i._callbacks={},i._taskCosts={},i._taskLoad=0,i.postMessage({type:"init",libraryConfig:this.libraryConfig}),i.onmessage=n=>{const s=n.data;switch(s.type){case"warning":this.warnings.push(s.data),console.warn(s.data);break;case"decode":i._callbacks[s.id].resolve(s);break;case"error":i._callbacks[s.id].reject(s);break;default:console.error('THREE.Rhino3dmLoader: Unexpected message, "'+s.type+'"')}},this.workerPool.push(i)}else this.workerPool.sort(function(i,n){return i._taskLoad>n._taskLoad?-1:1});const t=this.workerPool[this.workerPool.length-1];return t._taskLoad+=e,t})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this}}const Dz=`
function Rhino3dmWorker() {

	let libraryPending;
	let libraryConfig;
	let rhino;
	let taskID;

	onmessage = function ( e ) {

		const message = e.data;

		switch ( message.type ) {

			case 'init':

				libraryConfig = message.libraryConfig;
				const wasmBinary = libraryConfig.wasmBinary;
				let RhinoModule;
				libraryPending = new Promise( function ( resolve ) {

					/* Like Basis Loader */
					RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };

					rhino3dm( RhinoModule ); // eslint-disable-line no-undef

				 } ).then( () => {

					rhino = RhinoModule;

				 } );

				break;

			case 'decode':

				taskID = message.id;
				const buffer = message.buffer;
				libraryPending.then( () => {

					try {

						const data = decodeObjects( rhino, buffer );
						self.postMessage( { type: 'decode', id: message.id, data } );

					} catch ( error ) {

						self.postMessage( { type: 'error', id: message.id, error } );

					}

				} );

				break;

		}

	};

	function decodeObjects( rhino, buffer ) {

		const arr = new Uint8Array( buffer );
		const doc = rhino.File3dm.fromByteArray( arr );

		const objects = [];
		const materials = [];
		const layers = [];
		const views = [];
		const namedViews = [];
		const groups = [];
		const strings = [];

		//Handle objects

		const objs = doc.objects();
		const cnt = objs.count;

		for ( let i = 0; i < cnt; i ++ ) {

			const _object = objs.get( i );

			const object = extractObjectData( _object, doc );

			_object.delete();

			if ( object ) {

				objects.push( object );

			}

		}

		// Handle instance definitions
		// console.log( \`Instance Definitions Count: \${doc.instanceDefinitions().count()}\` );

		for ( let i = 0; i < doc.instanceDefinitions().count; i ++ ) {

			const idef = doc.instanceDefinitions().get( i );
			const idefAttributes = extractProperties( idef );
			idefAttributes.objectIds = idef.getObjectIds();

			objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );

		}

		// Handle materials

		const textureTypes = [
			// rhino.TextureType.Bitmap,
			rhino.TextureType.Diffuse,
			rhino.TextureType.Bump,
			rhino.TextureType.Transparency,
			rhino.TextureType.Opacity,
			rhino.TextureType.Emap
		];

		const pbrTextureTypes = [
			rhino.TextureType.PBR_BaseColor,
			rhino.TextureType.PBR_Subsurface,
			rhino.TextureType.PBR_SubsurfaceScattering,
			rhino.TextureType.PBR_SubsurfaceScatteringRadius,
			rhino.TextureType.PBR_Metallic,
			rhino.TextureType.PBR_Specular,
			rhino.TextureType.PBR_SpecularTint,
			rhino.TextureType.PBR_Roughness,
			rhino.TextureType.PBR_Anisotropic,
			rhino.TextureType.PBR_Anisotropic_Rotation,
			rhino.TextureType.PBR_Sheen,
			rhino.TextureType.PBR_SheenTint,
			rhino.TextureType.PBR_Clearcoat,
			rhino.TextureType.PBR_ClearcoatBump,
			rhino.TextureType.PBR_ClearcoatRoughness,
			rhino.TextureType.PBR_OpacityIor,
			rhino.TextureType.PBR_OpacityRoughness,
			rhino.TextureType.PBR_Emission,
			rhino.TextureType.PBR_AmbientOcclusion,
			rhino.TextureType.PBR_Displacement
		];

		for ( let i = 0; i < doc.materials().count; i ++ ) {

			const _material = doc.materials().get( i );

			const material = extractProperties( _material );

			const textures = [];

			textures.push( ...extractTextures( _material, textureTypes, doc ) );

			material.pbrSupported = _material.physicallyBased().supported;

			if ( material.pbrSupported ) {

				textures.push( ...extractTextures( _material, pbrTextureTypes, doc ) );
				material.pbr = extractProperties( _material.physicallyBased() );

			}

			material.textures = textures;

			materials.push( material );

			_material.delete();

		}

		// Handle layers

		for ( let i = 0; i < doc.layers().count; i ++ ) {

			const _layer = doc.layers().get( i );
			const layer = extractProperties( _layer );

			layers.push( layer );

			_layer.delete();

		}

		// Handle views

		for ( let i = 0; i < doc.views().count; i ++ ) {

			const _view = doc.views().get( i );
			const view = extractProperties( _view );

			views.push( view );

			_view.delete();

		}

		// Handle named views

		for ( let i = 0; i < doc.namedViews().count; i ++ ) {

			const _namedView = doc.namedViews().get( i );
			const namedView = extractProperties( _namedView );

			namedViews.push( namedView );

			_namedView.delete();

		}

		// Handle groups

		for ( let i = 0; i < doc.groups().count; i ++ ) {

			const _group = doc.groups().get( i );
			const group = extractProperties( _group );

			groups.push( group );

			_group.delete();

		}

		// Handle settings

		const settings = extractProperties( doc.settings() );

		//TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.

		// Handle dimstyles
		// console.log( \`Dimstyle Count: \${doc.dimstyles().count()}\` );

		// Handle bitmaps
		// console.log( \`Bitmap Count: \${doc.bitmaps().count()}\` );

		// Handle strings
		// console.log( \`Document Strings Count: \${doc.strings().count()}\` );
		// Note: doc.strings().documentUserTextCount() counts any doc.strings defined in a section
		// console.log( \`Document User Text Count: \${doc.strings().documentUserTextCount()}\` );

		const strings_count = doc.strings().count;

		for ( let i = 0; i < strings_count; i ++ ) {

			strings.push( doc.strings().get( i ) );

		}

		// Handle Render Environments for Material Environment

		// get the id of the active render environment skylight, which we'll use for environment texture
		const reflectionId = doc.settings().renderSettings().renderEnvironments.reflectionId;

		const rc = doc.renderContent();

		let renderEnvironment = null;

		for ( let i = 0; i < rc.count; i ++ ) {

			const content = rc.get(i);

			switch ( content.kind ) {

				case 'environment':

					const id = content.id;

					// there could be multiple render environments in a 3dm file
					if ( id !== reflectionId ) break;

					const renderTexture = content.findChild( 'texture' );
					const fileName = renderTexture.fileName;

					for ( let j = 0; j < doc.embeddedFiles().count; j ++ ) {

						const _fileName = doc.embeddedFiles().get( j ).fileName;

						if ( fileName === _fileName ) {

							const background = doc.getEmbeddedFileAsBase64( fileName );
							const backgroundImage = 'data:image/png;base64,' + background;
							renderEnvironment = { type: 'renderEnvironment', image: backgroundImage, name: fileName };

						}

					}

					break;

			}

		}

		// Handle Render Settings

		const renderSettings = {
			ambientLight: doc.settings().renderSettings().ambientLight,
			backgroundColorTop: doc.settings().renderSettings().backgroundColorTop,
			backgroundColorBottom: doc.settings().renderSettings().backgroundColorBottom,
			useHiddenLights: doc.settings().renderSettings().useHiddenLights,
			depthCue: doc.settings().renderSettings().depthCue,
			flatShade: doc.settings().renderSettings().flatShade,
			renderBackFaces: doc.settings().renderSettings().renderBackFaces,
			renderPoints: doc.settings().renderSettings().renderPoints,
			renderCurves: doc.settings().renderSettings().renderCurves,
			renderIsoParams: doc.settings().renderSettings().renderIsoParams,
			renderMeshEdges: doc.settings().renderSettings().renderMeshEdges,
			renderAnnotations: doc.settings().renderSettings().renderAnnotations,
			useViewportSize: doc.settings().renderSettings().useViewportSize,
			scaleBackgroundToFit: doc.settings().renderSettings().scaleBackgroundToFit,
			transparentBackground: doc.settings().renderSettings().transparentBackground,
			imageDpi: doc.settings().renderSettings().imageDpi,
			shadowMapLevel: doc.settings().renderSettings().shadowMapLevel,
			namedView: doc.settings().renderSettings().namedView,
			snapShot: doc.settings().renderSettings().snapShot,
			specificViewport: doc.settings().renderSettings().specificViewport,
			groundPlane: extractProperties( doc.settings().renderSettings().groundPlane ),
			safeFrame: extractProperties( doc.settings().renderSettings().safeFrame ),
			dithering: extractProperties( doc.settings().renderSettings().dithering ),
			skylight: extractProperties( doc.settings().renderSettings().skylight ),
			linearWorkflow: extractProperties( doc.settings().renderSettings().linearWorkflow ),
			renderChannels: extractProperties( doc.settings().renderSettings().renderChannels ),
			sun: extractProperties( doc.settings().renderSettings().sun ),
			renderEnvironments: extractProperties( doc.settings().renderSettings().renderEnvironments ),
			postEffects: extractProperties( doc.settings().renderSettings().postEffects ),

		};

		doc.delete();

		return { objects, materials, layers, views, namedViews, groups, strings, settings, renderSettings, renderEnvironment };

	}

	function extractTextures( m, tTypes, d ) {

		const textures = [];

		for ( let i = 0; i < tTypes.length; i ++ ) {

			const _texture = m.getTexture( tTypes[ i ] );
			if ( _texture ) {

				let textureType = tTypes[ i ].constructor.name;
				textureType = textureType.substring( 12, textureType.length );
				const texture = extractTextureData( _texture, textureType, d );
				textures.push( texture );
				_texture.delete();

			}

		}

		return textures;

	}

	function extractTextureData( t, tType, d ) {

		const texture = { type: tType };

		const image = d.getEmbeddedFileAsBase64( t.fileName );

		texture.wrapU = t.wrapU;
		texture.wrapV = t.wrapV;
		texture.wrapW = t.wrapW;
		const uvw = t.uvwTransform.toFloatArray( true );

		texture.repeat = [ uvw[ 0 ], uvw[ 5 ] ];

		if ( image ) {

			texture.image = 'data:image/png;base64,' + image;

		} else {

			self.postMessage( { type: 'warning', id: taskID, data: {
				message: \`THREE.3DMLoader: Image for \${tType} texture not embedded in file.\`,
				type: 'missing resource'
			}

			} );

			texture.image = null;

		}

		return texture;

	}

	function extractObjectData( object, doc ) {

		const _geometry = object.geometry();
		const _attributes = object.attributes();
		let objectType = _geometry.objectType;
		let geometry, attributes, position, data, mesh;

		// skip instance definition objects
		//if( _attributes.isInstanceDefinitionObject ) { continue; }

		// TODO: handle other geometry types
		switch ( objectType ) {

			case rhino.ObjectType.Curve:

				const pts = curveToPoints( _geometry, 100 );

				position = {};
				attributes = {};
				data = {};

				position.itemSize = 3;
				position.type = 'Float32Array';
				position.array = [];

				for ( let j = 0; j < pts.length; j ++ ) {

					position.array.push( pts[ j ][ 0 ] );
					position.array.push( pts[ j ][ 1 ] );
					position.array.push( pts[ j ][ 2 ] );

				}

				attributes.position = position;
				data.attributes = attributes;

				geometry = { data };

				break;

			case rhino.ObjectType.Point:

				const pt = _geometry.location;

				position = {};
				const color = {};
				attributes = {};
				data = {};

				position.itemSize = 3;
				position.type = 'Float32Array';
				position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];

				const _color = _attributes.drawColor( doc );

				color.itemSize = 3;
				color.type = 'Float32Array';
				color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];

				attributes.position = position;
				attributes.color = color;
				data.attributes = attributes;

				geometry = { data };

				break;

			case rhino.ObjectType.PointSet:
			case rhino.ObjectType.Mesh:

				geometry = _geometry.toThreejsJSON();

				break;

			case rhino.ObjectType.Brep:

				const faces = _geometry.faces();
				mesh = new rhino.Mesh();

				for ( let faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {

					const face = faces.get( faceIndex );
					const _mesh = face.getMesh( rhino.MeshType.Any );

					if ( _mesh ) {

						mesh.append( _mesh );
						_mesh.delete();

					}

					face.delete();

				}

				if ( mesh.faces().count > 0 ) {

					mesh.compact();
					geometry = mesh.toThreejsJSON();
					faces.delete();

				}

				mesh.delete();

				break;

			case rhino.ObjectType.Extrusion:

				mesh = _geometry.getMesh( rhino.MeshType.Any );

				if ( mesh ) {

					geometry = mesh.toThreejsJSON();
					mesh.delete();

				}

				break;

			case rhino.ObjectType.TextDot:

				geometry = extractProperties( _geometry );

				break;

			case rhino.ObjectType.Light:

				geometry = extractProperties( _geometry );

				if ( geometry.lightStyle.name === 'LightStyle_WorldLinear' ) {

					self.postMessage( { type: 'warning', id: taskID, data: {
						message: \`THREE.3DMLoader: No conversion exists for \${objectType.constructor.name} \${geometry.lightStyle.name}\`,
						type: 'no conversion',
						guid: _attributes.id
					}

					} );

				}

				break;

			case rhino.ObjectType.InstanceReference:

				geometry = extractProperties( _geometry );
				geometry.xform = extractProperties( _geometry.xform );
				geometry.xform.array = _geometry.xform.toFloatArray( true );

				break;

			case rhino.ObjectType.SubD:

				// TODO: precalculate resulting vertices and faces and warn on excessive results
				_geometry.subdivide( 3 );
				mesh = rhino.Mesh.createFromSubDControlNet( _geometry, false );
				if ( mesh ) {

					geometry = mesh.toThreejsJSON();
					mesh.delete();

				}

				break;

				/*
				case rhino.ObjectType.Annotation:
				case rhino.ObjectType.Hatch:
				case rhino.ObjectType.ClipPlane:
				*/

			default:

				self.postMessage( { type: 'warning', id: taskID, data: {
					message: \`THREE.3DMLoader: Conversion not implemented for \${objectType.constructor.name}\`,
					type: 'not implemented',
					guid: _attributes.id
				}

				} );

				break;

		}

		if ( geometry ) {

			attributes = extractProperties( _attributes );
			attributes.geometry = extractProperties( _geometry );

			if ( _attributes.groupCount > 0 ) {

				attributes.groupIds = _attributes.getGroupList();

			}

			if ( _attributes.userStringCount > 0 ) {

				attributes.userStrings = _attributes.getUserStrings();

			}

			if ( _geometry.userStringCount > 0 ) {

				attributes.geometry.userStrings = _geometry.getUserStrings();

			}

			if ( _attributes.decals().count > 0 ) {

				self.postMessage( { type: 'warning', id: taskID, data: {
					message: \`THREE.3DMLoader: No conversion exists for the decals associated with this object.\`,
					type: 'no conversion',
					guid: _attributes.id
				}

				} );

			}

			attributes.drawColor = _attributes.drawColor( doc );

			objectType = objectType.constructor.name;
			objectType = objectType.substring( 11, objectType.length );

			return { geometry, attributes, objectType };

		} else {

			self.postMessage( { type: 'warning', id: taskID, data: {
				message: \`THREE.3DMLoader: \${objectType.constructor.name} has no associated mesh geometry.\`,
				type: 'missing mesh',
				guid: _attributes.id
			}

			} );

		}

	}

	function extractProperties( object ) {

		const result = {};

		for ( const property in object ) {

			const value = object[ property ];

			if ( typeof value !== 'function' ) {

				if ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) {

					result[ property ] = { name: value.constructor.name, value: value.value };

				} else if ( typeof value === 'object' && value !== null ) {

					result[ property ] = extractProperties( value );

				} else {

					result[ property ] = value;

				}

			} else {

				// these are functions that could be called to extract more data.
				//console.log( \`\${property}: \${object[ property ].constructor.name}\` );

			}

		}

		return result;

	}

	function curveToPoints( curve, pointLimit ) {

		let pointCount = pointLimit;
		let rc = [];
		const ts = [];

		if ( curve instanceof rhino.LineCurve ) {

			return [ curve.pointAtStart, curve.pointAtEnd ];

		}

		if ( curve instanceof rhino.PolylineCurve ) {

			pointCount = curve.pointCount;
			for ( let i = 0; i < pointCount; i ++ ) {

				rc.push( curve.point( i ) );

			}

			return rc;

		}

		if ( curve instanceof rhino.PolyCurve ) {

			const segmentCount = curve.segmentCount;

			for ( let i = 0; i < segmentCount; i ++ ) {

				const segment = curve.segmentCurve( i );
				const segmentArray = curveToPoints( segment, pointCount );
				rc = rc.concat( segmentArray );
				segment.delete();

			}

			return rc;

		}

		if ( curve instanceof rhino.ArcCurve ) {

			pointCount = Math.floor( curve.angleDegrees / 5 );
			pointCount = pointCount < 2 ? 2 : pointCount;
			// alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399

		}

		if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {

			const pLine = curve.tryGetPolyline();

			for ( let i = 0; i < pLine.count; i ++ ) {

				rc.push( pLine.get( i ) );

			}

			pLine.delete();

			return rc;

		}

		const domain = curve.domain;
		const divisions = pointCount - 1.0;

		for ( let j = 0; j < pointCount; j ++ ) {

			const t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );

			if ( t === domain[ 0 ] || t === domain[ 1 ] ) {

				ts.push( t );
				continue;

			}

			const tan = curve.tangentAt( t );
			const prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );

			// Duplicated from THREE.Vector3
			// How to pass imports to worker?

			const tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
			const ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];

			const denominator = Math.sqrt( tS * ptS );

			let angle;

			if ( denominator === 0 ) {

				angle = Math.PI / 2;

			} else {

				const theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
				angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );

			}

			if ( angle < 0.1 ) continue;

			ts.push( t );

		}

		rc = ts.map( t => curve.pointAt( t ) );
		return rc;

	}

}
`,Gi=class Gi extends f1{constructor(e){super(e),this.materials=[],this.setLibraryPath(Gi.LIBRARY_PATH)}_createMaterial(e){return Gi.ImportMaterials?super._createMaterial(e):this.materials[0]||new Ka({color:new se(1,1,1),metalness:.8,name:"default",side:Zi})}async loadAsync(e,t){const i=await super.loadAsync(e,t);i.rotateX(-Math.PI/2),i.userData.materials&&delete i.userData.materials;const n=i.userData.layers;return i.traverse(s=>{const a=s.userData.attributes?.castsShadows,o=s.userData.attributes?.receivesShadows;s.castShadow=a,s.receiveShadow=o;const l=s.userData.attributes?.layerIndex??s.userData.defAttributes?.layerIndex,c=n[l];c&&(s.userData.rhinoLayer=c),s.userData.rhino3dmRoot=i.uuid,Gi.LoadUserDataStrings||(s.userData.strings=[]),Gi.LoadUserDataWarnings||delete s.userData.warnings,this._hideLineMesh(s),this._useInstancedMesh(s),this._useMaterialSource(s,c)}),this.materials=[],i}_useMaterialSource(e,t){if(!Gi.ImportMaterials)return;const i=e;if(i.material?.name==="default"||Gi.ForceLayerMaterials){const n=i.userData.attributes?.materialSource||i.userData.defAttributes?.materialSource,s=i.userData.attributes?.colorSource||i.userData.defAttributes?.colorSource;if(!Gi.ForceLayerMaterials&&!n&&!s)return;Gi.ForceLayerMaterials||n?.value===0||n?.value===1&&s?.value===0?t&&(i.material=this._compareMaterials(this._createMaterial({diffuseColor:t.color,name:t.name,transparency:0,textures:[]}))):n?.value===3||n?.value===1&&s?.value===3?i.traverseAncestors(a=>{a?.material&&(i.material=a.material)}):n&&n.value!==1&&console.warn("Unknown material source",n,i,i.userData.attributes)}}_useInstancedMesh(e){if(!Gi.ReplaceWithInstancedMesh||e.children.length<=0)return;const t=e.children,i=t.map(s=>s.geometry);i.filter((s,a)=>i.indexOf(s)===a).forEach(s=>{const a=t.filter(l=>l.geometry===s),o=a.length>0?a.filter(l=>l.material===a[0].material):[];if(o.length>1){const l=new Bc(s,o[0].material,o.length);l.userData={...o[0].userData},l.userData.instanceUserData=[],l.userData.attributes=l.userData.defAttributes||l.userData.attributes,l.userData.defAttributes&&delete l.userData.defAttributes,l.name=l.userData.attributes?.name||o[0].name,o.forEach((c,h)=>{l.setMatrixAt(h,c.matrix),e.remove(c),l.userData.instanceUserData.push(c.userData)}),e.add(l)}})}_hideLineMesh(e){if(!Gi.HideLineMesh&&!Gi.HidePointMesh||e.children.length<=0)return;const t=[];e.traverse(i=>{(i&&Gi.HideLineMesh&&(i.isLine||i.isLineSegments)||Gi.HidePointMesh&&i.isPoints)&&t.push(i)}),t.forEach(i=>{i.userData.visible_3dm=i.visible,i.visible=!1})}};Gi.LIBRARY_PATH=`https://cdn.jsdelivr.net/npm/rhino3dm@${Vu("rhino3dm","8.0.1")}/`,Gi.ImportMaterials=!0,Gi.ForceLayerMaterials=!1,Gi.ReplaceWithInstancedMesh=!1,Gi.HideLineMesh=!1,Gi.HidePointMesh=!1,Gi.LoadUserDataStrings=!0,Gi.LoadUserDataWarnings=!0;let ur=Gi;const Vh=class Vh extends li{constructor(e){super(e)}load(e,t,i,n){const s=Vh.USE_CANVAS_TEXTURE?document.createElement("canvas"):void 0,a=Vh.USE_CANVAS_TEXTURE?new Wo(s):new Rt,o=new Gc(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(e,function(l){s?Vh.CopyImageToCanvas(s,l):a.image=l,a.needsUpdate=!0,t!==void 0&&t(a)},i,n),a}static CopyImageToCanvas(e,t){e.width=t.naturalWidth||t.width||512,e.height=t.naturalHeight||t.height||512;const i=e.getContext("2d");i?(i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0,e.width,e.height)):console.error("SVGTextureLoader: Failed to get canvas context.")}};Vh.USE_CANVAS_TEXTURE=Vu("svg-load-disable-canvas")!=="true";let pg=Vh;class p1 extends li{constructor(e){super(e)}load(e,t,i,n){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,a=di.get(e);if(a!==void 0)return s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a;const o=document.createElementNS("http://www.w3.org/1999/xhtml","video");function l(){o.removeEventListener("loadedmetadata",l,!1),o.removeEventListener("error",c,!1),di.add(e,o),t&&t(o),s.manager.itemEnd(e)}function c(h){o.removeEventListener("loadedmetadata",l,!1),o.removeEventListener("error",c,!1),n&&n(h),s.manager.itemError(e),s.manager.itemEnd(e)}return o.addEventListener("loadedmetadata",l,!1),o.addEventListener("error",c,!1),e.substr(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),s.manager.itemStart(e),o.src=e,o.preload="auto",o.autoplay=!0,o.setAttribute("webkit-playsinline","webkit-playsinline"),o.setAttribute("playsinline",""),o}}class m1 extends li{constructor(e){super(e)}load(e,t,i,n){const s=new p1(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a;const o=s.load(e,function(l){a||(a=new py(l)),a.format=Kt,a.minFilter=st,a.magFilter=st,a.colorSpace=vt,a.needsUpdate=!0,t!==void 0&&t(a)},i,n);return!a&&o&&(a=new py(o)),a}}const Wg=class Wg extends xd{constructor(){super(),this.processors=[],this.processors.push(dT)}register(e){return super.register(e)}async parseAsync(e,t){if(!e)throw new Error("No object to export");let i=!e.__isGLTFOutput&&(Array.isArray(e)||e.isObject3D)?await new Promise((n,s)=>this.parse(e,n,s,t)):e;for(const n of this.processors)i=await n(i,t);if(i&&i instanceof Blob)return i;if(i&&typeof i=="object"&&!i.byteLength)return new Blob([JSON.stringify(i,(n,s)=>n.startsWith("__")?void 0:s,t.jsonSpaces??2)],{type:"model/gltf+json"});if(i)return new Blob([i],{type:"model/gltf+binary"});throw new Error("GLTFExporter2.parse() failed")}parse(e,t,i,n={}){const s={binary:!1,trs:n.trs??!1,onlyVisible:n.onlyVisible??!1,truncateDrawRange:n.truncateDrawRange??!0,externalImagesInExtras:!n.embedUrlImages&&n.externalImagesInExtras||!1,maxTextureSize:n.maxTextureSize??1/0,animations:n.animations??[],includeCustomExtensions:n.includeCustomExtensions??!0,forceIndices:n.forceIndices??!1,exporterOptions:n,ignoreInvalidMorphTargetTracks:n.ignoreInvalidMorphTargetTracks,ignoreEmptyTextures:n.ignoreEmptyTextures};n.exportExt==="glb"&&(s.binary=!0);const a=o=>{t(Object.assign(o,{__isGLTFOutput:!0}))};return super.parse(e,a,i,s,new nT)}setup(e,t){for(const i of Wg.ExportExtensions)this.register(i);if(t)for(const i of t)this.register(i);return this.register(this.gltfViewerWriter(e)),this}gltfViewerWriter(e){return t=>({afterParse:i=>{i=Array.isArray(i)?i[0]:i;let n;if(!i?.userData?.rootSceneModelRoot||t.options?.exporterOptions?.viewerConfig===!1||i?.userData?.__exportViewerConfig===!1?(n=od(t.serializationMeta),fo.BundleExtraResources(t.json,n),fo.BundleArrayBuffers(n,t)):n=fo.ExportViewerConfig(e,t),!n||Object.values(n).reduce((o,l)=>o+Object.keys(l).length,0)===0)return;const a=t.json.extras||{};a[Ml.BundledResourcesKey]=n,t.json.extras=a}})}};Wg.ExportExtensions=[Md.Export,Td.Export,Ed.Export,Cl.Export,xl.Export,wl.Export,e=>({name:"_AssetPropsWriter",beforeParse:t=>{const i=Array.isArray(t)?t:[t];for(const n of i)n.userData.gltfExtras&&(n.__gltfExtras=n.userData.gltfExtras,delete n.userData.gltfExtras),n.userData.gltfAsset&&(n.__gltfAsset=n.userData.gltfAsset,delete n.userData.gltfAsset)},afterParse:t=>{const i=e.json.extras||{},n=Array.isArray(t)?t:[t];for(const s of n)s.__gltfAsset&&(s.userData.gltfAsset=s.__gltfAsset,delete s.__gltfAsset),s.__gltfExtras&&(s.userData.gltfExtras=s.__gltfExtras,Object.assign(i,s.userData.gltfExtras),delete s.__gltfExtras);Object.keys(i).length>0&&(e.json.extras=i)}})];let mg=Wg;class g1{async parseAsync(e,{jsonSpaces:t=2}){return new Blob([JSON.stringify(e,null,t)],{type:"application/json"})}}class A1{async parseAsync(e,t){return new Blob([e],{type:"text/plain"})}}const Rz=new TextEncoder,y1=3;class v1{parse(e,t,i){if(!e||!(e.isWebGLRenderer||e.isDataTexture))throw Error("EXRExporter.parse: Unsupported first parameter, expected instance of WebGLRenderer or DataTexture.");if(e.isWebGLRenderer){const n=e,s=t,a=i;Bz(s);const o=Oz(s,a),l=Fz(n,s,o),c=_1(l,o),h=b1(c,o);return w1(h,o)}else if(e.isDataTexture){const n=e,s=t;Lz(n);const a=Uz(n,s),o=n.image.data,l=_1(o,a),c=b1(l,a);return w1(c,a)}}}function Bz(r){if(!r||!r.isWebGLRenderTarget)throw Error("EXRExporter.parse: Unsupported second parameter, expected instance of WebGLRenderTarget.");if(r.isWebGLCubeRenderTarget||r.isWebGL3DRenderTarget||r.isWebGLArrayRenderTarget)throw Error("EXRExporter.parse: Unsupported render target type, expected instance of WebGLRenderTarget.");if(r.texture.type!==zt&&r.texture.type!==$t)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture type.");if(r.texture.format!==Kt)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture format, expected RGBAFormat.")}function Lz(r){if(r.type!==zt&&r.type!==$t)throw Error("EXRExporter.parse: Unsupported DataTexture texture type.");if(r.format!==Kt)throw Error("EXRExporter.parse: Unsupported DataTexture texture format, expected RGBAFormat.");if(!r.image.data)throw Error("EXRExporter.parse: Invalid DataTexture image data.");if(r.type===zt&&r.image.data.constructor.name!=="Float32Array")throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Float32Array'.");if(r.type===$t&&r.image.data.constructor.name!=="Uint16Array")throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Uint16Array'.")}function Oz(r,e={}){const t={0:1,2:1,3:16},i=r.width,n=r.height,s=r.texture.type,a=r.texture.format;texture.colorSpace;const o=e.compression!==void 0?e.compression:y1,l=e.type!==void 0?e.type:$t,c=l===zt?2:1,h=t[o];return{width:i,height:n,type:s,format:a,compression:o,blockLines:h,dataType:c,dataSize:2*c,numBlocks:Math.ceil(n/h),numInputChannels:4,numOutputChannels:4,textureIndex:e.textureIndex||0}}function Uz(r,e={}){const t={0:1,2:1,3:16},i=r.image.width,n=r.image.height,s=r.type,a=r.format,o=r.colorSpace,l=e.compression!==void 0?e.compression:y1,c=e.type!==void 0?e.type:$t,h=c===zt?2:1,u=t[l];return{width:i,height:n,type:s,format:a,colorSpace:o,compression:l,blockLines:u,dataType:h,dataSize:2*h,numBlocks:Math.ceil(n/u),numInputChannels:4,numOutputChannels:4,flipY:r.isDataTexture&&r.flipY,textureIndex:e.textureIndex||0}}function Fz(r,e,t){let i;return t.type===zt?i=new Float32Array(t.width*t.height*t.numInputChannels):i=new Uint16Array(t.width*t.height*t.numInputChannels),r.readRenderTargetPixels(e,0,0,t.width,t.height,i,void 0,t.textureIndex),i}function _1(r,e){const t=e.width,i=e.height,n={r:0,g:0,b:0,a:0},s={value:0},a=e.numOutputChannels==4?1:0,o=e.type==zt?Wz:jz,l=e.dataType==1?Vz:t_,c=new Uint8Array(e.width*e.height*e.numOutputChannels*e.dataSize),h=new DataView(c.buffer);for(let u=0;u<i;++u)for(let d=0;d<t;++d){const p=u*t*4+d*4,m=o(r,p),A=o(r,p+1),g=o(r,p+2),y=o(r,p+3),_=(e.flipY?u:i-u-1)*t*(3+a)*e.dataSize;zz(n,m,A,g,y),s.value=_+d*e.dataSize,l(h,n.a,s),s.value=_+a*t*e.dataSize+d*e.dataSize,l(h,n.b,s),s.value=_+(1+a)*t*e.dataSize+d*e.dataSize,l(h,n.g,s),s.value=_+(2+a)*t*e.dataSize+d*e.dataSize,l(h,n.r,s)}return c}function b1(r,e){let t,i,n=0;const s={data:new Array,totalSize:0},a=e.width*e.numOutputChannels*e.blockLines*e.dataSize;switch(e.compression){case 0:t=Nz;break;case 2:case 3:t=kz;break}e.compression!==0&&(i=new Uint8Array(a));for(let o=0;o<e.numBlocks;++o){const l=r.subarray(a*o,a*(o+1)),c=t(l,i);n+=c.length,s.data.push({dataChunk:c,size:c.length})}return s.totalSize=n,s}function Nz(r){return r}function kz(r,e){let t=0,i=Math.floor((r.length+1)/2),n=0;const s=r.length-1;for(;!(n>s||(e[t++]=r[n++],n>s));)e[i++]=r[n++];let a=e[0];for(let l=1;l<e.length;l++){const c=e[l]-a+384;a=e[l],e[l]=c}return lg(e)}function Gz(r,e,t){const i={value:0},n=new DataView(r.buffer);Yt(n,20000630,i),Yt(n,2,i),mn(n,"compression",i),mn(n,"compression",i),Yt(n,1,i),kd(n,t.compression,i),mn(n,"screenWindowCenter",i),mn(n,"v2f",i),Yt(n,8,i),Yt(n,0,i),Yt(n,0,i),mn(n,"screenWindowWidth",i),mn(n,"float",i),Yt(n,4,i),t_(n,1,i),mn(n,"pixelAspectRatio",i),mn(n,"float",i),Yt(n,4,i),t_(n,1,i),mn(n,"lineOrder",i),mn(n,"lineOrder",i),Yt(n,1,i),kd(n,0,i),mn(n,"dataWindow",i),mn(n,"box2i",i),Yt(n,16,i),Yt(n,0,i),Yt(n,0,i),Yt(n,t.width-1,i),Yt(n,t.height-1,i),mn(n,"displayWindow",i),mn(n,"box2i",i),Yt(n,16,i),Yt(n,0,i),Yt(n,0,i),Yt(n,t.width-1,i),Yt(n,t.height-1,i),mn(n,"channels",i),mn(n,"chlist",i),Yt(n,t.numOutputChannels*18+1,i),mn(n,"A",i),Yt(n,t.dataType,i),i.value+=4,Yt(n,1,i),Yt(n,1,i),mn(n,"B",i),Yt(n,t.dataType,i),i.value+=4,Yt(n,1,i),Yt(n,1,i),mn(n,"G",i),Yt(n,t.dataType,i),i.value+=4,Yt(n,1,i),Yt(n,1,i),mn(n,"R",i),Yt(n,t.dataType,i),i.value+=4,Yt(n,1,i),Yt(n,1,i),kd(n,0,i),kd(n,0,i);let s=i.value+t.numBlocks*8;for(let a=0;a<e.data.length;++a)Hz(n,s,i),s+=e.data[a].size+8}function w1(r,e){const t=e.numBlocks*8,i=259+18*e.numOutputChannels,n={value:i+t},s=new Uint8Array(i+t+r.totalSize+e.numBlocks*8),a=new DataView(s.buffer);Gz(s,r,e);for(let o=0;o<r.data.length;++o){const l=r.data[o].dataChunk,c=r.data[o].size;Yt(a,o*e.blockLines,n),Yt(a,c,n),s.set(l,n.value),n.value+=c}return s}function zz(r,e,t,i,n){r.r=e,r.g=t,r.b=i,r.a=n}function kd(r,e,t){r.setUint8(t.value,e),t.value+=1}function Yt(r,e,t){r.setUint32(t.value,e,!0),t.value+=4}function Vz(r,e,t){r.setUint16(t.value,Hn.toHalfFloat(e),!0),t.value+=2}function t_(r,e,t){r.setFloat32(t.value,e,!0),t.value+=4}function Hz(r,e,t){r.setBigUint64(t.value,BigInt(e),!0),t.value+=8}function mn(r,e,t){const i=Rz.encode(e+"\0");for(let n=0;n<i.length;++n)kd(r,i[n],t)}function Qz(r){const e=(r&31744)>>10,t=r&1023;return(r>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function jz(r,e){return Qz(r[e])}function Wz(r,e){return r[e]}class i_ extends v1{async parseAsync(e,t){const i=e;if(i.isWebGLRenderTarget&&!i.renderManager)throw new Error("No renderManager on renderTarget");if(!i.isWebGLRenderTarget&&!e.isDataTexture)throw new Error("Invalid object type");i.isWebGLRenderTarget&&i.textures.length>1&&t.textureIndex===void 0&&console.warn("RenderTarget has multiple textures, but no textureIndex specified. Using texture 0.");const n=i.isWebGLRenderTarget?this.parse(i.renderManager.webglRenderer,i,t):this.parse(e,t);return new Blob([n],{type:"image/x-exr"})}}const C1=(r,e)=>{const t=r.exportOptions||{},i=r.obj.isMaterial?r.obj:null,n=r.obj.isObject3D?r.obj:null;if(r.state==="processing"){if(i){const s=e.replaceTexture?_e.getMapsForMaterial.call(i):null,a=s&&e.replaceTexture?x1(s,i,i,e.replaceTexture):null;i.__exportState={savedMaps:a}}if(n){const{objectList:s,meshLines:a,fomMap:o,geomMap:l,matCloneMap:c,savedTextures:h}=n.__exportState={objectList:new Set,meshLines:new Map,fomMap:new Map,geomMap:new Map,matCloneMap:new Map,savedTextures:new Map};n.traverse(d=>{d?.isObject3D&&(s.add(d),d.children&&d._sChildren&&(d._tChildren=d.children,d.children=d._sChildren))});const u=new Map;s.forEach(d=>{t.preserveUUIDs!==!1&&d.uuid&&(d.userData.gltfUUID=d.uuid),e.object&&e.object(d,n),Xz(d,t);const p=qz(d,n,e.objectGeometry);p&&(e.objectGeometryReplace&&e.objectGeometryReplace(d,p),l.set(d,d.forcedOverrideGeometry),d.forcedOverrideGeometry=p);const m=a.has(d)?null:Yz(d);m&&a.set(d,m),e.objectMaterials&&e.objectMaterials(d,n.material);const A=$z(d,c,u,n,e.objectMaterial);A!==void 0&&(e.objectMaterialsReplace&&e.objectMaterialsReplace(d,A),o.set(d,d.forcedOverrideMaterial),d.forcedOverrideMaterial=A);const g=Ge.getMapsForObject3D.call(d);u.set(d,g)}),e.replaceTexture&&u.forEach((d,p)=>{const m=x1(d,p,n,e.replaceTexture);h.set(p,m)}),u.clear()}}if((r.state==="done"||r.state==="error")&&(i&&i.__exportState&&(e.revertTextures&&e.revertTextures(i),S1(i.__exportState.savedMaps,i),delete i.__exportState),n&&n.__exportState)){const{objectList:s,meshLines:a,fomMap:o,geomMap:l,matCloneMap:c,savedTextures:h}=n.__exportState;delete n.__exportState,s.forEach(u=>{t.preserveUUIDs!==!1&&u.userData.gltfUUID&&delete u.userData.gltfUUID,Kz(u,a.get(u)),e.revertObject&&e.revertObject(u),u._tChildren&&(u.children=u._tChildren,delete u._tChildren)}),a.clear(),s.clear(),new Set([...c.values()]).forEach(u=>{u.dispose&&u.dispose()}),c.clear(),o.forEach((u,d)=>{u!==void 0?d.forcedOverrideMaterial=u:delete d.forcedOverrideMaterial}),o.clear(),l.forEach((u,d)=>{u!==void 0?d.forcedOverrideGeometry=u:delete d.forcedOverrideGeometry}),l.clear(),e.revertTextures&&h.forEach((u,d)=>{e.revertTextures&&e.revertTextures(d),S1(u,d)}),h.clear()}};function x1(r,e,t,i){const n={},s={};return r.forEach((a,o)=>{if(!i)return;const l=i(e,a,o,t);l!==a&&(n[o]=l,s[o]=a)}),Mm(n,e),s}function S1(r,e){r&&Mm(r,e)}function qz(r,e,t){const i=r.geometry;if(!i)return;let n=null;if(i.userData.isPlaceholder)n=Bs.DummyGeometry;else if(t){const s=t(r,i,e);s&&(n=s)}if(n&&n!==i)return n}function Xz(r,e){if(r.animations){e.animations||(e.animations=[]);for(const t of r.animations){if(t.__gltfExport===!1)continue;const i=t.userData.rootRefs||[];e.preserveUUIDs!==!1&&r.uuid?i.includes(r.uuid)||i.push(r.uuid):r.name&&(i.includes(r.name)||i.push(r.name)),t.userData.rootRefs=i,e.animations.includes(t)||e.animations.push(t)}}}function Yz(r){const e=r,t=e.geometry;if(typeof t?.getPositions=="function"&&r.isLine===void 0&&r.isLineSegments===void 0&&(r.isLine2||r.isLineSegments2)){const i=t.getPositions();if(i){const n=t.getColors&&e.geometry.getColors(),s=new $e;s.attributes.position=new Xe(i,3),n&&(s.attributes.color=new Xe(n,3)),s.name=t.name,s.userData=t.userData,s.uuid=t.uuid;const a=r.geometry;return r.assetType?r._currentGeometry=s:r.geometry=s,e.isLine2?r.isLine=!0:e.isLineSegments2&&(r.isLine=!0,r.isLineSegments=!0),a}}}function $z(r,e,t,i,n){if(!r.material)return;const s=r.material,a=Array.isArray(s),o=a?s:[s];let l=a?[...s]:s;const c=(h,u,d)=>{let p=e.get(u);p||(p=d(),e.set(u,p)),a?l[h]=p:l=p};if(o.forEach((h,u)=>{if(h.userData.isPlaceholder)c(u,h,()=>Bs.DummyMaterial);else{const d=n?n(r,h,i,u):null;if(d)c(u,h,d);else{const p=_e.getMapsForMaterial.call(h);t.set(h,p),h.userData.sProperties!==void 0&&c(u,h,()=>{const m=new h.constructor;m.name=h.name;const A=gE(h,h.userData.sProperties);return Mm(A,m),m.userData.uuid=h.uuid,m.userData.sProperties=h.userData.sProperties,m.userData.rootPath=h.userData.rootPath,m.userData.rootPathOptions=h.userData.rootPathOptions,m})}}}),a?l.some((h,u)=>h!==s[u]):l!==s)return l}function Kz(r,e){if(e&&r.geometry){const t=r.geometry;r.assetType?r._currentGeometry=e:r.geometry=e,t.dispose(!0),r.isLine&&delete r.isLine,r.isLineSegments&&delete r.isLineSegments}}class E1 extends wi{constructor(){super(),this.exporters=[{ctor:()=>new g1,ext:["json"]},{ctor:()=>new A1,ext:["txt","text"]},{ctor:()=>new i_,ext:["exr"]}],this.exportHooks={},this._cachedWriters=[],this.addEventListener("exportFile",e=>C1(e,this.exportHooks))}addExporter(...e){for(const t of e){if(this.exporters.includes(t)){console.warn("Exporter already added",t);return}this.exporters.push(t)}}removeExporter(...e){for(const t of e){const i=this.exporters.indexOf(t);i>=0&&this.exporters.splice(i,1)}}getExporter(...e){return this.exporters.find(t=>t.ext.some(i=>e.includes(i)))}async exportObject(e,t={}){if(!e?.assetType){console.error("Object has no asset type");return}const i=[];e.assetType==="model"&&e.traverse(s=>{s.userData.excludeFromExport&&s.visible&&(s.visible=!1,i.push(s))});const n=await this._exportFile(e,t);return e.assetType==="model"&&i.forEach(s=>s.visible=!0),e?.userData?.rootSceneModelRoot&&t.viewerConfig===!1&&delete e.userData.__exportViewerConfig,n}async _exportFile(e,t={}){let i;try{this.dispatchEvent({type:"exportFile",obj:e,state:"processing",exportOptions:t});const n=await this.processBeforeExport(e,t),s=n?.typeExt||n?.ext;if(!n||!s)throw console.error(n,t,e),new Error(`AssetExporter - Unable to preprocess before export ${s}`);if(n.blob)i=n.blob;else{const a=this._getWriter(s);this.dispatchEvent({type:"exportFile",obj:e,state:"exporting",exportOptions:t}),i=await a.parseAsync(n.obj,{exportExt:n.ext??s,...t}),i.ext=n.ext}i=await this.processAfterExport(i,e,t),this.dispatchEvent({type:"exportFile",obj:e,state:"done",exportOptions:t})}catch(n){throw console.error("AssetExporter: Unable to Export file",e),this.dispatchEvent({type:"exportFile",obj:e,state:"error",error:n,exportOptions:t}),n}return i}_createParser(e){const t=this.exporters.find(n=>n.ext.includes(e));if(!t)throw new Error(`No exporter found for extension ${e}`);const i=t?.ctor(this,t);if(!i)throw new Error(`Unable to create writer for extension ${e}`);return this._cachedWriters.push({ext:t.ext,parser:i}),this.dispatchEvent({type:"exporterCreate",exporter:t,parser:i}),i}_getWriter(e){return this._cachedWriters.find(t=>t.ext.includes(e))?.parser??this._createParser(e)}async processBeforeExport(e,t={}){switch(e.assetType){case"light":console.error("AssetExporter: light export not implemented");return;case"model":return{obj:e,ext:t.exportExt??"glb"};case"material":return{obj:Jz(e),ext:t.exportExt||e.constructor?.TypeSlug,typeExt:"json"};case"texture":return t.exportExt?{obj:e,ext:t.exportExt}:{obj:e.toJSON(),ext:"json"};case"renderTarget":if(e.renderManager){const i=t.exportExt&&t.exportExt!=="auto"?t.exportExt==="exr"?"image/x-exr":"image/"+t.exportExt:"auto";let n;if(e.textures.length>1){const s={};for(let o=0;o<e.textures.length;o++){const l=e.renderManager.exportRenderTarget(e,i,o);s[`texture_${o}.${l.ext}`]=new Uint8Array(l.__buffer||await l.arrayBuffer())}const a=hg(s);n=new Blob([a],{type:"application/zip"}),n.ext="zip",n.__buffer=a.buffer}else n=e.renderManager.exportRenderTarget(e,i);return{obj:e,ext:n.ext,blob:n}}else return{obj:e,ext:"exr"};default:console.error("AssetExporter: unknown asset type",e.assetType)}}async processAfterExport(e,t,i={}){return e}dispose(){}}function Jz(r){return r.toJSON()}class M1 extends wi{constructor(){super(),this._materials=[],this._disposeMaterial=e=>{const t=e.target;!t||t.assetType!=="material"||this.unregisterMaterial(t)},this._registerMaterial=e=>{const t=e.target;!t||t.assetType!=="material"||this.registerMaterial(t)},this.unregisterExtensionsOnRemove=!1,this._materialExtensions=[],Zz()}findOrCreate(e,t){let i=this.findMaterial(e);return i||(i=this.create(e,t)),i}create(e,t={},i=!0,n){const s=this.findTemplate(e);if(!s){console.error("No material template found for type",e);return}const a=this._create(s,t);return n&&an(a,"uuid",n,!0,!0),a&&i&&this.registerMaterial(a),a}_create(e,t){if(!e){console.error("No material template provided");return}const i=new e;return t&&i&&i.setValues(t,!0),i}registerMaterial(e){if(!e||this._materials.includes(e))return;e.assetType||CM.call(e),this.findMaterial(e.uuid)&&(an(e,"uuid",Ui(),!0,!0),e.userData.uuid&&(e.userData.uuid=e.uuid)),e.addEventListener("__unregister",this._disposeMaterial),e.addEventListener("__register",this._registerMaterial),e.registerMaterialExtensions?.(this._materialExtensions),e.setDirty(),this._materials.push(e)}registerMaterials(e){e.forEach(t=>this.registerMaterial(t))}unregisterMaterial(e){this._materials=this._materials.filter(t=>t.uuid!==e.uuid),this.unregisterExtensionsOnRemove&&e.unregisterMaterialExtensions?.(this._materialExtensions),e.removeEventListener("__unregister",this._disposeMaterial),e.removeEventListener("__register",this._registerMaterial)}clearMaterials(){[...this._materials].forEach(e=>this.unregisterMaterial(e))}dispose(e=!0){const t=this._materials;this._materials=[];for(const i of t){if(!e&&i.userData.runtimeMaterial){this._materials.push(i);continue}i.dispose()}}findMaterial(e){return e?this._materials.find(t=>t.uuid===e):void 0}findMaterialsByName(e,t=!1){return this._materials.filter(i=>typeof e!="string"||t?i.name.match(typeof e=="string"?"^"+e+"$":e)!==null:i.name===e)}getMaterialsOfType(e){return e?this._materials.filter(t=>t.constructor.TypeSlug===e):[]}getAllMaterials(){return[...this._materials]}convertToIMaterial(e,{useSourceMaterial:t=!0,materialTemplate:i,createFromTemplate:n=!0}={}){if(!e)return;if(e.assetType)return e;if(e.iMaterial?.assetType)return e.iMaterial;const s=e.userData?.uuid||e.uuid;let a=this.findMaterial(s);if(!a&&n!==!1){const o=t===!1||!e.isMaterial,l=i||!o&&e.type&&e.type||"physical";a=this.create(l,o?void 0:e)}else a&&(console.warn("Material with the same uuid already exists, copying properties"),e.type!==a.type&&console.error("Material type mismatch, delete previous material first?",e,a),a.setValues(e));return a?(a.uuid=s,a.userData.uuid=s,e.iMaterial=a):(console.warn("Failed to convert material to IMaterial, just upgrading",e,t,i),a=_e.upgradeMaterial.call(e)),a}registerMaterialExtension(e){if(!this._materialExtensions.includes(e)){this._materialExtensions.push(e);for(const t of this._materials)t.registerMaterialExtensions?.([e])}}unregisterMaterialExtension(e){const t=this._materialExtensions.indexOf(e);if(!(t<0)){this._materialExtensions.splice(t,1);for(const i of this._materials)i.unregisterMaterialExtensions?.([e])}}clearExtensions(){[...this._materialExtensions].forEach(e=>this.unregisterMaterialExtension(e))}exportMaterial(e,t,i=!0,n=!1){const s=e.toJSON(),a=JSON.stringify(s,null,i?0:2),o=(t||e.name||"physical_material")+"."+e.constructor.TypeSlug,l=new File([a],o,{type:"application/json"});return n&&jx(l),l}applyMaterial(e,t,i=!0,n){let s=this.findMaterialsByName(t,i);(!s||s.length<1)&&(s=[this.findMaterial(t)]);let a=!1;for(const o of s){if(!o||o===e||o.userData.__isVariation)continue;this.copyMaterialProps(o,e,n)&&(a=!0)}return a}copyMaterialProps(e,t,i){let n=!1;const s=Object.getPrototypeOf(t).constructor.TYPE;if(Object.getPrototypeOf(e).constructor.TYPE===s){const o=e.name;e.setValues(t,void 0,void 0,i),e.name=o,n=!0}else{const o=e["__"+s]||this.create(s);if(o){const l=e.name;o.setValues?o.setValues(t):Object.assign(o,t),o.name=l;const c=e.appliedMeshes;for(const h of[...c??[]])h&&(h.material=o,n=!0);e["__"+s]=o}}return n}registerMaterialTemplate(e){if(!e||ke.SerializableMaterials.has(e))return;const t=[...ke.SerializableMaterials.values()].find(i=>i.TYPE===e.TYPE);t&&console.warn("Material template with the same type already exists",e,t),ke.SerializableMaterials.add(e)}unregisterMaterialTemplate(e){e&&ke.SerializableMaterials.delete(e)}findTemplate(e){if(e)return[...ke.SerializableMaterials.values()].find(t=>t.TYPE===e)||[...ke.SerializableMaterials.values()].find(t=>t.TypeAlias?.includes(e))}}function Zz(){const r=`
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
`;ot.bumpmap_pars_fragment=At(ot.bumpmap_pars_fragment,r,`
    #ifdef BUMP_MAP_SCALE_LEGACY
        ${r.replace(/normalize/g,"")}
    #else
        ${r}
    #endif
    `)}class T1 extends Iy{constructor(e){super(e),this.type=$t}parse(e){const a=function(S,w){switch(S){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(w||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(w||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(w||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(w||""))}},u=function(S,w,C){w=w||1024;let O=S.pos,F=-1,G=0,j="",W=String.fromCharCode.apply(null,new Uint16Array(S.subarray(O,O+128)));for(;0>(F=W.indexOf(`
`))&&G<w&&O<S.byteLength;)j+=W,G+=W.length,O+=128,W+=String.fromCharCode.apply(null,new Uint16Array(S.subarray(O,O+128)));return-1<F?(S.pos+=G+F+1,j+W.slice(0,F)):!1},d=function(S){const w=/^#\?(\S+)/,C=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,D=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,O=/^\s*FORMAT=(\S+)\s*$/,F=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,G={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let j,W;for((S.pos>=S.byteLength||!(j=u(S)))&&a(1,"no header found"),(W=j.match(w))||a(3,"bad initial token"),G.valid|=1,G.programtype=W[1],G.string+=j+`
`;j=u(S),j!==!1;){if(G.string+=j+`
`,j.charAt(0)==="#"){G.comments+=j+`
`;continue}if((W=j.match(C))&&(G.gamma=parseFloat(W[1])),(W=j.match(D))&&(G.exposure=parseFloat(W[1])),(W=j.match(O))&&(G.valid|=2,G.format=W[1]),(W=j.match(F))&&(G.valid|=4,G.height=parseInt(W[1],10),G.width=parseInt(W[2],10)),G.valid&2&&G.valid&4)break}return G.valid&2||a(3,"missing format specifier"),G.valid&4||a(3,"missing image size specifier"),G},p=function(S,w,C){const D=w;if(D<8||D>32767||S[0]!==2||S[1]!==2||S[2]&128)return new Uint8Array(S);D!==(S[2]<<8|S[3])&&a(3,"wrong scanline width");const O=new Uint8Array(4*w*C);O.length||a(4,"unable to allocate buffer space");let F=0,G=0;const j=4*D,W=new Uint8Array(4),K=new Uint8Array(j);let q=C;for(;q>0&&G<S.byteLength;){G+4>S.byteLength&&a(1),W[0]=S[G++],W[1]=S[G++],W[2]=S[G++],W[3]=S[G++],(W[0]!=2||W[1]!=2||(W[2]<<8|W[3])!=D)&&a(3,"bad rgbe scanline format");let oe=0,re;for(;oe<j&&G<S.byteLength;){re=S[G++];const Ie=re>128;if(Ie&&(re-=128),(re===0||oe+re>j)&&a(3,"bad scanline data"),Ie){const Ue=S[G++];for(let te=0;te<re;te++)K[oe++]=Ue}else K.set(S.subarray(G,G+re),oe),oe+=re,G+=re}const Ce=D;for(let Ie=0;Ie<Ce;Ie++){let Ue=0;O[F]=K[Ie+Ue],Ue+=D,O[F+1]=K[Ie+Ue],Ue+=D,O[F+2]=K[Ie+Ue],Ue+=D,O[F+3]=K[Ie+Ue],F+=4}q--}return O},m=function(S,w,C,D){const O=S[w+3],F=Math.pow(2,O-128)/255;C[D+0]=S[w+0]*F,C[D+1]=S[w+1]*F,C[D+2]=S[w+2]*F,C[D+3]=1},A=function(S,w,C,D){const O=S[w+3],F=Math.pow(2,O-128)/255;C[D+0]=Hn.toHalfFloat(Math.min(S[w+0]*F,65504)),C[D+1]=Hn.toHalfFloat(Math.min(S[w+1]*F,65504)),C[D+2]=Hn.toHalfFloat(Math.min(S[w+2]*F,65504)),C[D+3]=Hn.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const y=d(g),_=y.width,v=y.height,b=p(g.subarray(g.pos),_,v);let T,E,M;switch(this.type){case zt:M=b.length/4;const S=new Float32Array(M*4);for(let C=0;C<M;C++)m(b,C*4,S,C*4);T=S,E=zt;break;case $t:M=b.length/4;const w=new Uint16Array(M*4);for(let C=0;C<M;C++)A(b,C*4,w,C*4);T=w,E=$t;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:_,height:v,data:T,header:y.string,gamma:y.gamma,exposure:y.exposure,type:E}}setDataType(e){return this.type=e,this}load(e,t,i,n){function s(a,o){switch(a.type){case zt:case $t:a.colorSpace=Dt,a.minFilter=st,a.magFilter=st,a.generateMipmaps=!1,a.flipY=!0;break}t&&t(a,o)}return super.load(e,s,i,n)}}function eV(r,e){const t=(r.version?r.version:"0.0.0").split(".").map(n=>parseInt(n));if(!(r.type==="ViewerApp"&&t[0]===0&&(t[1]<7||t[1]===7&&t[2].toString()[0]<"6")))return;const i=new Set;e.forEach(n=>n.traverse(s=>{s.material&&i.add(s.material)})),i.forEach(n=>{const s=n.map;if(!s)return;const a=s.repeat,o=s.offset,l=s.center,c=s.rotation;["alphaMap","aoMap","bumpMap","displacementMap","emissiveMap","lightMap","metalnessMap","normalMap","roughnessMap","transmissionMap"].forEach(u=>{const d=n[u];d&&(d.repeat.copy(a),d.offset.copy(o),d.center.copy(l),d.rotation=c,d.needsUpdate=!0)}),n.needsUpdate=!0})}class tV extends xt{constructor(e){super(e),xt.ObjectConstructors.MeshStandardMaterial=ai,xt.ObjectConstructors.MeshBasicMaterial=ys,xt.ObjectConstructors.MeshPhysicalMaterial=ai,xt.ObjectConstructors.LineBasicMaterial=$n}transform(e,t){let i;return e.scene.traverse(n=>{if(i)return;const s=n.material;s&&s.isPhysicalMaterial&&(i=s)}),i}}const Z_=class Z_ extends wi{constructor(e,t){super(),this._gltfExporter={ext:["gltf","glb"],extensions:[],ctor:(i,n)=>{const s=new mg;return s.setup(this.viewer,n.extensions),s}},this.processState=new Map,this.gltfExtensions=[],this._sceneUpdated=this._sceneUpdated.bind(this),this.addAsset=this.addAsset.bind(this),this.addRaw=this.addRaw.bind(this),this._loaderCreate=this._loaderCreate.bind(this),this.addImported=this.addImported.bind(this),this.importer=new Bs(!!e.getPlugin("debug"),t),this.exporter=new E1,this.materials=new M1,this.viewer=e,this.viewer.scene.addEventListener("addSceneObject",this._sceneUpdated),this.viewer.scene.addEventListener("materialChanged",this._sceneUpdated),this.viewer.scene.addEventListener("beforeDeserialize",this._sceneUpdated),this._setupGltfExtensions(),this._setupObjectProcess(),this._setupObjectExport(),this._setupProcessState(),this._addImporters(),this._addExporters()}get storage(){return this.importer.storage}async addAsset(e,t){if(!this.importer||!this.viewer)return[];const i=await this.importer.import(e,t);if(!i){const n=typeof e=="string"?e:e?.path;return n&&!n.split("?")[0].endsWith(".vjson")&&console.warn("Threepipe AssetManager - Unable to import",e,i),[]}return this.loadImported(i,t)}async loadImported(e,{autoSetEnvironment:t=!0,autoSetBackground:i=!1,...n}={}){const s=Array.isArray(e)?e:[e];let a=Array.isArray(e)?[]:void 0;if(n?.importConfig!==!1){const o=s.find(l=>l?.assetType==="config")||s.find(l=>l&&!!l.importedViewerConfig)?.importedViewerConfig;o&&eV(o,s.filter(l=>l?.isObject3D))}for(const o of s){if(!o){Array.isArray(a)&&a.push(void 0);continue}let l=o;const c=o?.__rootBlob?o.__rootBlob.filePath||o.__rootBlob.name:o.__rootPath||o.userData?.rootPath||o.name||"";switch(o.assetType){case"material":this.materials.registerMaterial(o);break;case"texture":t&&(c?.endsWith(".hdr")||c?.endsWith(".exr"))&&(this.viewer.scene.environment=o),i&&(this.viewer.scene.background=o);break;case"model":case"light":case"camera":l=await this.viewer.addSceneObject(o,n);break;case"config":n?.importConfig!==!1&&await this.viewer.importConfig(o);break;default:o.type&&typeof o.type=="string"&&(Array.isArray(o.plugins)||o.type==="ThreeViewer"||this.viewer.getPlugin(o.type))&&await this.viewer.importConfig(o);break}this.dispatchEvent({type:"loadAsset",data:o}),Array.isArray(a)?a.push(l):a=l}return a}async addProcessedAssets(e,t){return this.loadImported(e,t)}async addAssetSingle(e,t){return e?(await this.addAsset(e,t))?.[0]:void 0}async addRaw(e,t={}){const i=await this.importer.processRaw(e,t);return this.loadImported(i,t)}async addRawSingle(e,t={}){return(await this.addRaw(e,t))?.[0]}_sceneUpdated(e){if(e.type==="addSceneObject"){const i=e.object;switch(i.assetType){case"material":this.materials.registerMaterial(i);break}}else if(e.type==="materialChanged"){const i=e.material,n=Array.isArray(i)?i:i?[i]:[];for(const s of n)this.materials.registerMaterial(s)}else if(e.type==="beforeDeserialize"){const t=e,i=t.data,n=t.meta;i.metadata||console.warn("Invalid data(no metadata)",i),t.material&&(i.metadata?.type!=="Material"&&console.warn("Invalid material data",i),oh.DeserializeMaterialJSON(i,this.viewer,n,t.material).then(()=>{}))}else console.error("Unexpected")}dispose(){this.importer.dispose(),this.materials.dispose(),this.processState.clear(),this.viewer.scene.removeEventListener("addSceneObject",this._sceneUpdated),this.viewer.scene.removeEventListener("materialChanged",this._sceneUpdated),this.exporter.dispose()}_addImporters(){const e=this.viewer;if(!e)return;const t=this.importer,i=[new qi(class extends Pd{async parseAsync(n){if(n.assetType==="config")return n;const s=n.type||n.metadata?.type,a=t.importers.filter(o=>{const l=o.cls?.SupportedJSONTypes;if(l)return it(l)?.includes(s)});for(const o of a){if(!o)continue;const l=o.ctor(t),c=await l.parseAsync(n);if(l.dispose&&l.dispose(),c)return c}if(n.serializableClassId){const o=n.resources;n.resources&&delete n.resources;const l=o?await e.loadConfigResources(o):void 0,c=ke.Deserialize(n,void 0,l);if(l&&(n.resources=l),c)return c}return super.parseAsync(n)}},["json","vjson"],["application/json"],!1),new qi(pg,["svg","data:image/svg"],["image/svg+xml"],!1),new qi(to,["webp","png","jpeg","jpg","ico","data:image","avif","bmp","gif","tiff"],["image/webp","image/png","image/jpeg","image/gif","image/bmp","image/tiff","image/x-icon","image/avif"],!1),new qi(oh,oh.SupportedJSONExtensions,[],!1,n=>(n&&(n.viewer=this.viewer),n)),new qi(class extends T1{constructor(n){super(n),this.setDataType(Sv(e.renderManager.renderer))}},["hdr"],["image/vnd.radiance"],!1),new qi(class extends Z0{constructor(n){super(n),this.setDataType(Sv(e.renderManager.renderer))}},["exr"],["image/x-exr"],!1),new qi(c1,["fbx"],["model/fbx"],!0),new qi(h1,["zip","glbz","gltfz"],["application/zip","model/gltf+zip","model/zip"],!0),new qi(yT,["obj"],["model/obj"],!0),new qi(T0,["mtl"],["model/mtl"],!1),new qi(Ml,["gltf","glb","data:model/gltf","data:model/glb"],["model/gltf","model/gltf+json","model/gltf-binary","model/glb"],!0,(n,s,a)=>n?.setup(this.viewer,a.extensions)),new qi(fg,["drc"],["model/mesh+draco","model/drc"],!0),new qi(m1,["mp4","ogg","mov","webm","data:video"],["video/mp4","video/ogg","video/quicktime","video/webm"],!0),new qi(tV,["phmatgltf"],[],!0)];this.importer.addImporter(...i)}_addExporters(){const e=[this._gltfExporter];this.exporter.addExporter(...e)}_setupObjectProcess(){this.importer.addEventListener("processRaw",e=>{if(e.data&&e.data.isObject3D){const i=e.data;this._loadObjectDependencies(i);return}const t=e.data;t&&t.isMaterial&&t.uuid&&this.materials.registerMaterial(t)}),this.importer.addEventListener("processRawStart",e=>iV(e,this))}_setupObjectExport(){}async _loadObjectDependencies(e){const t=[];if(!e.traverseModels){this.viewer.console.error("AssetManager - Object not upgraded, cannot load dependencies",e);return}e.traverseModels&&e.traverseModels(s=>s.userData.rootPathRefresh&&!s._rootPathRefreshed&&!s._rootPathRefreshing&&s.userData.rootPath?(t.push(s),!1):!0,{visible:!1,widgets:!0});const i=t.map(async s=>{s._rootPathRefreshing=!0;const a=s.userData.rootPath;if(!a)return null;const o=s.userData.rootPathOptions,l=await this.importer.import(a,{...o});if(!l)throw new Error(`Unable to load asset from url - ${a}`);return l}),n=await Promise.allSettled(i);for(let s=0;s<n.length;s++){const a=n[s],o=t[s];if(delete o._rootPathRefreshing,o._rootPathRefreshed=!0,a.status==="rejected"){this.viewer.console.error(`ThreeViewer - Failed to load root path for object ${o.name}`,a.reason);continue}if(a.status!=="fulfilled")continue;const l=a.value;if(!l||!l.length)continue;const c=l.find(m=>m?.isObject3D);if(!c){this.viewer.console.warn("AssetManager - No valid model found in root path",a.value);continue}const h=l.filter(m=>m&&m!==c),u=o.parent,d=u?u.children.indexOf(o):-1;if(u&&o.removeFromParent(),this.viewer.object3dManager.unregisterObject(o),!c.isObject3D){this.viewer.console.warn("Non model dependency loaded. Not fully supported yet.");continue}if(!u){this.viewer.console.error("AssetManager - Unexpected error, no parent found for object when loading dependency",o);continue}c._copyFromEmbedded?c._copyFromEmbedded(o):(o.matrix.decompose(c.position,c.quaternion,c.scale),c.name=o.name,c.userData={...o.userData,...c.userData},c._rootPathRefreshed=!0,c.uuid=o.uuid),u.add(c);const p=u.children.indexOf(c);if(d>=0&&p>=0&&d!==p&&(u.children.splice(p,1),u.children.splice(d,0,c)),h.length)for(const m of h)m?.isObject3D?u.add(m):this.viewer.console.warn("Non model dependency loaded. Not fully supported yet.",m)}}setProcessState(e,t){t===void 0?this.processState.delete(e):this.processState.set(e,t),this.dispatchEvent({type:"processStateUpdate"})}_setupProcessState(){this.importer.addEventListener("importFile",e=>{!e.path||e.path.startsWith("blob:")||e.path.startsWith("data:")||this.setProcessState(e.path,e.state!=="done"?{state:e.state,progress:e.progress?e.progress*100:void 0}:void 0)}),this.importer.addEventListener("processRawStart",e=>{!e.path||e.path.startsWith("blob:")||e.path.startsWith("data:")||this.setProcessState(e.path,{state:"processing",progress:void 0})}),this.importer.addEventListener("processRaw",e=>{!e.path||e.path.startsWith("blob:")||e.path.startsWith("data:")||this.setProcessState(e.path,void 0)}),this.exporter.addEventListener("exportFile",e=>{e.obj.name&&this.setProcessState(e.obj.name,e.state!=="done"?{state:e.state,progress:e.progress?e.progress*100:void 0}:void 0)})}_setupGltfExtensions(){this.importer.addEventListener("loaderCreate",this._loaderCreate),this.viewer.forPlugin("GLTFDracoExportPlugin",e=>{if(e.addExtension)for(const t of this.gltfExtensions)e.addExtension(t.name,t.textures)})}_loaderCreate({loader:e}){if(e.isGLTFLoader2)for(const t of this.gltfExtensions)e.register(t.import)}registerGltfExtension(e){const t=this.gltfExtensions.findIndex(n=>n.name===e.name);t>=0&&this.gltfExtensions.splice(t,1),this.gltfExtensions.push(e),this._gltfExporter.extensions.push(e.export);const i=this.exporter.getExporter("gltf","glb");i&&i!==this._gltfExporter&&i.extensions?.push(e.export)}unregisterGltfExtension(e){const t=this.gltfExtensions.findIndex(s=>s.name===e);if(t<0)return;this.gltfExtensions.splice(t,1);const i=this._gltfExporter.extensions.findIndex(s=>s.name===e);i>=0&&this._gltfExporter.extensions.splice(i,1);const n=this.exporter.getExporter("gltf","glb");if(n?.extensions&&n!==this._gltfExporter){const s=n.extensions.findIndex(a=>a.name===e);s>=0&&n.extensions?.splice(s,1)}}async addImported(e,t={}){return console.error("addImported is deprecated, use addRaw instead"),this.addRaw(e,t)}async addFromPath(e,t={}){return console.error("addFromPath is deprecated, use addAsset instead"),this.addAsset(e,t)}exportViewerConfig(e=!0){return this.viewer?(console.error("exportViewerConfig is deprecated, use viewer.toJSON instead"),this.viewer.toJSON(e,void 0)):{}}exportPluginPresets(e){return console.error("exportPluginPresets is deprecated, use viewer.exportPluginsConfig instead"),this.viewer?.exportPluginsConfig(e)}exportPluginPreset(e){return console.error("exportPluginPreset is deprecated, use viewer.exportPluginConfig instead"),this.viewer?.exportPluginConfig(e)}async importPluginPreset(e,t){return console.error("importPluginPreset is deprecated, use viewer.importPluginConfig instead"),this.viewer?.importPluginConfig(e,t)}async importViewerConfig(e){return this.viewer?.importConfig(e)}applyViewerConfig(e,t){return console.error("applyViewerConfig is deprecated, use viewer.fromJSON instead"),this.viewer?.fromJSON(e,t)}async importConfigResources(e,t){if(!this.importer)throw"Importer not initialized yet.";return e.__isLoadedResources?e:this.viewer?.loadConfigResources(e,t)}};Z_.PluginType="AssetManager";let gg=Z_;const iV=(r,e)=>{const t=r.data,i=r.options;if(t.isObject3D){const n=[],s=[];t.traverse(a=>{if(a.material){const o=Array.isArray(a.material)?a.material:[a.material],l=[],c=[];for(const h of o){const u=e.materials.convertToIMaterial(h,{createFromTemplate:i.replaceMaterials!==!1})||h;u.uuid=h.uuid,u.userData.uuid=h.uuid,l.push(u);const d=_e.getMapsForMaterial.call(u);c.push(...Array.from(d.values()))}Array.isArray(a.material)?a.material=l:a.material=l[0],new Set(c).forEach(h=>{typeof h.userData.rootPath=="string"&&h.userData.rootPath.startsWith("blob:")&&delete h.userData.rootPath,h.userData.rootPath&&!h.__rootPath?(h.__rootPath=h.userData.rootPath,e.importer.processRawSingle(h,{})):bd.call(h)})}a.isCamera&&n.push(a),a.isLight&&s.push(a)});for(const a of n)if(a.assetType!=="camera")if(!a.parent||i.replaceCameras===!1)ct.upgradeCamera.call(a);else{const o=a.iCamera??!a.isOrthographicCamera?new th("",e.viewer.canvas):new yd("",e.viewer.canvas);if(a===o)continue;a.parent.children.splice(a.parent.children.indexOf(a),1,o),o.parent=a.parent,o.copy(a),a.parent=null,o.uuid=a.uuid,o.userData.uuid=a.uuid,a.iCamera=o}for(const a of s)if(a.assetType!=="light")if(!a.parent||i.replaceLights===!1)pn.upgradeLight.call(a);else{const o=a.iLight??a.isDirectionalLight?new Qm:a.isPointLight?new jm:a.isSpotLight?new Wm:a.isAmbientLight?new vl:a.isHemisphereLight?new Ca:a.isRectAreaLight?new Nr:void 0;if(a===o||!o)continue;a.parent.children.splice(a.parent.children.indexOf(a),1,o),o.parent=a.parent,o.copy(a),a.parent=null,o.uuid=a.uuid,o.userData.uuid=a.uuid,a.iLight=o}Ge.upgradeObject3D.call(t)}else t.isMaterial?t.assetType||_e.upgradeMaterial.call(t):t.isTexture&&(bd.call(t),r?.options?.generateMipmaps!==void 0&&(t.generateMipmaps=r?.options.generateMipmaps),!t.generateMipmaps&&!t.isRenderTargetTexture&&(t.minFilter=t.minFilter===Ln?st:t.minFilter,t.magFilter=t.magFilter===Ln?st:t.magFilter))},kl=class kl extends wi{constructor(){super(),this._objects=new Map,this._objectExtensions=[],this._materials=new Map,this._geometries=new Map,this._textures=new Map,this._videos=new Map,this._lights=new Map,this.autoDisposeTextures=!0,this.autoDisposeMaterials=!0,this.autoDisposeGeometries=!0,this.autoDisposeObjects=!1,this._rootChanged=e=>{if(!e.target||!this._root)return;const t=e.target.parentRoot;let i=!1;t===this._root?i=!0:e.target.traverseAncestors(n=>{n===this._root&&(i=!0)}),i?this.registerObject(e.target):this.unregisterObject(e.target)},this._materialChanged=e=>{if(!e.target)return;const t=e.target,i=e.oldMaterial;i&&(Array.isArray(i)?this._unregisterMaterials(i,t):this._unregisterMaterial(i,t)),this._registerMaterials(t.materials,t)},this._geometryChanged=e=>{if(!e.target)return;const t=e.target,i=e.oldGeometry;i&&this._unregisterGeometry(i,t),this._registerGeometry(t.geometry,t)},this._texturesChanged=e=>{if(!e.target)return;const t=e.target,i=e.removedTextures;if(i)for(const s of i)this._unregisterTexture(s,t);const n=e.textures;if(n)for(const s of n)this._registerTexture(s,t)},this._textureChanged=e=>{e.target&&(e.oldTexture&&this._unregisterTexture(e.oldTexture,e.target),e.texture&&this._registerTexture(e.texture,e.target))},this._rootChanged=this._rootChanged.bind(this),this._materialChanged=this._materialChanged.bind(this),this._geometryChanged=this._geometryChanged.bind(this),this._texturesChanged=this._texturesChanged.bind(this)}onPostFrame(e){for(const t of this._videos.values()){const i=t.userData.timeline;if(i&&!i.enabled)continue;const n=t.image,s=i?.delay||0,a=i?.scale||1,o=i?.start||0,l=n.duration||1,c=l-(i?.end||0);let h=e.time;if(h-=s,h*=a,h<o&&(h=o),h>c&&(h=c),h<0&&(h=0),h>l&&(h=l),Math.abs(h-n.currentTime)>1/60&&(n.currentTime=h,n.paused)){const d=(t._playid||0)+1;t._playid=d,n.play().then(()=>{t._playid===d&&(n.paused||n.pause(),delete t._playid)})}e.running||!n.paused&&!t._playid&&n.pause()}}setRoot(e){this._root=e}registerObject(e){if(!e||!e.uuid||!e.isObject3D)return;const t=this.getObject(e.uuid);if(t)if(e!==t)console.warn("Object3DManager - Object with the same uuid already registered",e,t),an(e,"uuid",Ui(),!0,!0);else return;e.assetType||Ge.upgradeObject3D.call(e),this._objects.set(e.uuid,e),e.addEventListener("parentRootChanged",this._rootChanged),e.addEventListener("materialChanged",this._materialChanged),e.addEventListener("geometryChanged",this._geometryChanged),e.addEventListener("texturesChanged",this._texturesChanged),e.isScene&&(e.addEventListener("backgroundChanged",this._textureChanged),e.addEventListener("environmentChanged",this._textureChanged)),this._registerMaterials(e.materials,e),this._registerGeometry(e.geometry,e);const i=Ge.getMapsForObject3D.call(e);if(i)for(const s of i.values())this._registerTexture(s,e);e.objectExtensions||(e.objectExtensions=[]);const n=e.objectExtensions;for(const s of this._objectExtensions){if(n.includes(s))continue;(s.isCompatible?s.isCompatible(e):!0)&&(n.push(s),s.onRegister&&s.onRegister(e))}this.dispatchEvent({type:"objectAdd",object:e}),e.isLight&&(this._lights.set(e.uuid,e),this.dispatchEvent({type:"lightAdd",light:e})),e.dispatchEvent({type:"__register"})}unregisterObject(e){if(!e||!e.uuid)return!1;const t=this._objects.get(e.uuid);if(!t)return!1;if(e!==t)return console.error("Object3DManager - Object to unregister is not the same as the registered object",e,t),!1;this._objects.delete(e.uuid),e.removeEventListener("materialChanged",this._materialChanged),e.removeEventListener("geometryChanged",this._geometryChanged),e.removeEventListener("texturesChanged",this._texturesChanged),e.isScene&&(e.removeEventListener("backgroundChanged",this._textureChanged),e.removeEventListener("environmentChanged",this._textureChanged)),this._unregisterMaterials(e.materials,e),this._unregisterGeometry(e.geometry,e);const i=Ge.getMapsForObject3D.call(e);if(i)for(const n of i.values())this._unregisterTexture(n,e);return this.autoDisposeObjects&&e.userData?.disposeOnIdle!==!1&&e.dispose&&e.dispose(!1),this.dispatchEvent({type:"objectRemove",object:e}),e.isLight&&this._lights.has(e.uuid)&&(this._lights.delete(e.uuid),this.dispatchEvent({type:"lightRemove",light:e})),e.dispatchEvent({type:"__unregister"}),!0}registerObjectExtension(e){if(!(!e||(e.uuid||(e.uuid=Ui()),this._objectExtensions.includes(e)))){this._objectExtensions.push(e);for(const i of this._objects.values())i.objectExtensions&&!i.objectExtensions.includes(e)&&(!e.isCompatible||e.isCompatible(i))&&i.objectExtensions.push(e)}}unregisterObjectExtension(e){if(!e)return;const t=this._objectExtensions.indexOf(e);t<0||this._objectExtensions.splice(t,1)}_registerMaterials(e,t){return e&&e.forEach(i=>this._registerMaterial(i,t))}_unregisterMaterials(e,t){return e&&e.forEach(i=>this._unregisterMaterial(i,t))}_registerMaterial(e,t){if(!e||!e.isMaterial||!t||!e.uuid)return;e.assetType||_e.upgradeMaterial.call(e);let i=e.appliedMeshes;i||(i=new Set,e.appliedMeshes=i);const n=this.getMaterial(e.uuid);n&&e!==n&&(console.warn("Object3DManager - Material with the same uuid already registered",e,n),an(e,"uuid",Ui(),!0,!0));const s=!this._materials.has(e.uuid);i.add(t),this._materials.set(e.uuid,e),s&&e.addEventListener("texturesChanged",this._texturesChanged);const a=_e.getMapsForMaterial.call(e);if(a)for(const o of a.values())this._registerTexture(o,e);s&&(this.dispatchEvent({type:"materialAdd",material:e}),e.dispatchEvent({type:"__register"}))}_unregisterMaterial(e,t){if(!e||!t||!t.uuid)return;const i=e.appliedMeshes;if(!i)return;i.delete(t);const n=this.getMaterial(e.uuid);if(n&&e!==n){console.error("Object3DManager - Material to unregister is not the same as the registered material",e,n);return}if(i.size===0&&n){this._materials.delete(e.uuid),e.removeEventListener("texturesChanged",this._texturesChanged);const s=_e.getMapsForMaterial.call(e);if(s)for(const a of s.values())this._unregisterTexture(a,e);this.dispatchEvent({type:"materialRemove",material:e}),this.autoDisposeMaterials&&e.dispose(!1),e.dispatchEvent({type:"__unregister"})}}_registerGeometry(e,t){if(!e||!e.isBufferGeometry||!t||!t.uuid)return;e.assetType||ri.upgradeGeometry.call(e);let i=e.appliedMeshes;i||(i=new Set,e.appliedMeshes=i);const n=this.getGeometry(e.uuid);n&&e!==n&&(console.warn("Object3DManager - Geometry with the same uuid already registered",e,n),an(e,"uuid",Ui(),!0,!0));const s=!this._geometries.has(e.uuid);i.add(t),this._geometries.set(e.uuid,e),s&&(this.dispatchEvent({type:"geometryAdd",geometry:e}),e.dispatchEvent({type:"__register"}))}_unregisterGeometry(e,t){if(!e||!t||!t.uuid)return;const i=e.appliedMeshes;if(!i)return;i.delete(t);const n=this.getGeometry(e.uuid);n&&e!==n&&console.error("Object3DManager - Geometry to unregister is not the same as the registered geometry",e,n),i.size===0&&this._geometries.has(e.uuid)&&(this._geometries.delete(e.uuid),this.dispatchEvent({type:"geometryRemove",geometry:e}),this.autoDisposeGeometries&&e.dispose(!1),e.dispatchEvent({type:"__unregister"}))}_registerTexture(e,t){if(!e||!e.isTexture||!t||!t.uuid)return;e.assetType||bd.call(e);let i=e.appliedObjects;i||(i=new Set,e.appliedObjects=i);const n=this.getTexture(e.uuid);n&&e!==n&&(console.warn("Object3DManager - Texture with the same uuid already registered",e,n),an(e,"uuid",Ui(),!0,!0));const s=!this._textures.has(e.uuid);i.add(t),this._textures.set(e.uuid,e),e.isVideoTexture&&this._registerVideo(e),s&&(this.dispatchEvent({type:"textureAdd",texture:e}),e.dispatchEvent({type:"__register"}))}_unregisterTexture(e,t){if(!e||!t||!t.uuid)return;const i=e.appliedObjects;if(!i)return;i.delete(t);const n=this.getTexture(e.uuid);if(n&&e!==n){console.error("Object3DManager - Texture to unregister is not the same as the registered texture",e,n);return}i.size===0&&this._textures.has(e.uuid)&&(this._textures.delete(e.uuid),e.isVideoTexture&&this._videos.delete(e.uuid),this.dispatchEvent({type:"textureRemove",texture:e}),e.userData?.disposeOnIdle!==!1&&this.autoDisposeTextures&&!e.isRenderTargetTexture&&e.dispose&&e.dispose(),e.dispatchEvent({type:"__unregister"}),e.isVideoTexture&&(e.image,this.dispatchEvent({type:"videoRemove",video:e})))}_registerVideo(e){this._videos.set(e.uuid,e);const t=e.image;t.preload="auto",t.autoplay=!0,t.loop=!0,t.muted=!0,this.dispatchEvent({type:"videoAdd",video:e})}findObject(e){if(!e)return;const t=this.getObject(e);if(t)return t;const i=this.findObjectsByName(e);if(i.length>1){console.warn("Multiple objects found with name:",e,i);return}return i[0]}findObjectsByName(e){const t=[];return this._objects.forEach(i=>{i.name===e&&t.push(i)}),t}findMaterial(e){if(!e)return;const t=this.getMaterial(e);if(t)return t;const i=this.findMaterialsByName(e);if(i.length>1){console.warn("Multiple materials found with name:",e,i);return}return i[0]}findMaterialsByName(e){const t=[];return this._materials.forEach(i=>{i.name===e&&t.push(i)}),t}dispose(){const e=[...this._objects.values()];for(const t of e)this.unregisterObject(t),t.removeEventListener("parentRootChanged",this._rootChanged);this._objectExtensions=[],this._objects.clear(),this._materials.clear(),this._geometries.clear(),this.dispatchEvent({type:"dispose"})}getObjects(){return[...this._objects.values()]}getObject(e){return this._objects.get(e)}getObjectExtensions(){return[...this._objectExtensions]}getMaterials(){return[...this._materials.values()]}getMaterial(e){return this._materials.get(e)}getGeometries(){return[...this._geometries.values()]}getGeometry(e){return this._geometries.get(e)}getTextures(){return[...this._textures.values()]}getTexture(e){return this._textures.get(e)}getVideos(){return[...this._videos.values()]}getVideo(e){return this._videos.get(e)}getLights(){return[...this._lights.values()]}getLight(e){return this._lights.get(e)}};kl.MaterialTextureProperties=bM,kl.MaterialTexturePropertiesUserData=wM,kl.SceneTextureProperties=EM,kl.Object3DTextureProperties=MM,new Set([...ys.MapProperties,...$n.MapProperties,...ai.MapProperties,...Gm.MapProperties]).forEach(e=>kl.MaterialTextureProperties.add(e));let Ag=kl;var nV=Object.defineProperty,sV=Object.getOwnPropertyDescriptor,zr=(r,e,t,i)=>{for(var n=i>1?void 0:i?sV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&nV(e,t,n),n};f.RenderManager=class extends XM{constructor({canvas:e,alpha:t=!0,renderScale:i=1,powerPreference:n,targetOptions:s}){super(),this._renderSize=new $(512,512),this._renderScale=1,this._passes=[],this._pipeline=[],this._passesNeedsUpdate=!0,this._frameCount=0,this._lastTime=0,this._totalFrameCount=0,this.stableNoise=!1,this.frameWaitTime=0,this._dirty=!0,this.autoBuildPipeline=!0,this.defaultRenderToScreen=!0,this.onPostFrame=()=>{for(const o of this._passes)o.enabled&&o.onPostFrame&&o.onPostFrame?.(this)},this.animationLoop=this.animationLoop.bind(this),this._renderSize=new $(e.clientWidth,e.clientHeight),this._renderScale=i,this._renderer=this._initWebGLRenderer(e,t,s?.stencilBuffer??!1,n),this._context=this._renderer.getContext(),this._isWebGL2=this._renderer.capabilities.isWebGL2,this._isWebGL2||console.error("RenderManager: WebGL 1 is not officially supported anymore. Some features may not work."),this.resetShadows();const a=this.createTarget(s,!1);a.texture.name="EffectComposer.rt1",this._composer=new WM(this._renderer,a)}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this.setSize(void 0,void 0,!0))}_shadowMapTypeChanged(){this.resetShadows(),this.reset()}get renderer(){return this._renderer}rebuildPipeline(e=!0){this._passesNeedsUpdate=!0,e&&(this._updated({change:"rebuild"}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1))}_refreshPipeline(){if(!this.autoBuildPipeline)return this._pipeline;const e=this._passes;try{this._pipeline=HM(e)}catch(t){console.error("RenderManager: Unable to sort rendering passes",t)}return this._pipeline}animationLoop(e,t){const i=e-this._lastTime;this._lastTime=e,this.frameWaitTime-=i,!(this.frameWaitTime>0)&&(this.frameWaitTime=0,this.dispatchEvent({type:"animationLoop",deltaTime:i,time:e,renderer:this._renderer,xrFrame:t}))}_initWebGLRenderer(e,t,i,n){const s=new Xf({canvas:e,antialias:!1,alpha:t,premultipliedAlpha:!1,preserveDrawingBuffer:!0,powerPreference:n??f.RenderManager.POWER_PREFERENCE,stencil:i});return s.setAnimationLoop(this.animationLoop),s.onContextLost=a=>{this.dispatchEvent({type:"contextLost",event:a})},s.onContextRestore=()=>{this.dispatchEvent({type:"contextRestored"})},s.setSize(this._renderSize.width,this._renderSize.height,!1),s.setPixelRatio(this._renderScale),s.toneMapping=$r,s.toneMappingExposure=1,s.outputColorSpace=si,s.shadowMap.enabled=!0,s.shadowMap.type=Kg,s.shadowMap.autoUpdate=!1,NM.call(s,this)}setSize(e,t,i=!1){!i&&(e?Math.abs(e-this._renderSize.width):0)+(t?Math.abs(t-this._renderSize.height):0)<.1||(e&&(this._renderSize.width=e),t&&(this._renderSize.height=t),this.webglRenderer.xr.enabled&&this.webglRenderer.xr.isPresenting||(this._renderer.setSize(this._renderSize.width,this._renderSize.height,!1),this._renderer.setPixelRatio(this._renderScale)),this._composer.setPixelRatio(this._renderScale,!1),this._composer.setSize(this._renderSize.width,this._renderSize.height),this.resizeTrackedTargets(),this.dispatchEvent({type:"resize"}),this._updated({change:"size",data:this._renderSize.toArray()}),this.reset(),this.uiConfig?.uiRefresh?.(!0,"postFrame",0))}render(e,t){this._passesNeedsUpdate&&(this._refreshPipeline(),this.refreshPasses());for(const i of this._passes)i.enabled&&i.beforeRender&&i.beforeRender(e,e.renderCamera,this);this._composer.renderToScreen=t??this.defaultRenderToScreen,this.dispatchEvent({type:"preRender",scene:e,renderToScreen:this._composer.renderToScreen}),this._composer.render(),this.dispatchEvent({type:"postRender",scene:e,renderToScreen:this._composer.renderToScreen}),this._composer.renderToScreen=!0,t&&this.incRenderToScreen(),this._dirty=!1}incRenderToScreen(){this._frameCount+=1,this._totalFrameCount+=1}get needsRender(){return this.renderSize.x<1||this.renderSize.y<1?!1:(this._dirty=this._dirty||this._passes.findIndex(e=>it(e.dirty))>=0,this._dirty)}setDirty(e=!1){this._dirty=!0,e&&this.reset()}reset(){this._frameCount=0,this._dirty=!0}resetShadows(){this._renderer.shadowMap.needsUpdate=!0}refreshPasses(){if(!this._passesNeedsUpdate)return;this._passesNeedsUpdate=!1;const e=[];for(const t of this._pipeline){const i=this._passes.find(n=>n.passId===t);if(!i){console.warn("Unable to find pass: ",t);continue}e.push(i)}[...this._composer.passes].forEach(t=>this._composer.removePass(t)),e.forEach(t=>this._composer.addPass(t)),this._updated({change:"passRefresh"}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}dispose(e=!0){super.dispose(e),this._renderer.dispose()}updateShaderProperties(e){return e.uniforms.currentFrameCount&&(e.uniforms.currentFrameCount.value=this.frameCount),this.stableNoise?e.uniforms.frameCount?e.uniforms.frameCount.value=this.frameCount:console.warn("RenderManager: no uniform: frameCount"):e.uniforms.frameCount?e.uniforms.frameCount.value=this._totalFrameCount:console.warn("RenderManager: no uniform: frameCount"),this}registerPass(e,t=!0){if(t)for(const i of[...this._passes])e.passId===i.passId&&this.unregisterPass(i);this._passes.push(e),e.onRegister?.(this),this.rebuildPipeline(!1),this._updated({change:"registerPass",pass:e}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}unregisterPass(e){const t=this._passes.indexOf(e);t>=0&&(e.onUnregister?.(this),this._passes.splice(t,1),this.rebuildPipeline(!1),this._updated({change:"unregisterPass",pass:e}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1))}get frameCount(){return this._frameCount}get totalFrameCount(){return this._totalFrameCount}resetTotalFrameCount(){this._totalFrameCount=0}set pipeline(e){this._pipeline=e,this.autoBuildPipeline&&console.warn("RenderManager: pipeline changed, but autoBuildPipeline is true. This will not have any effect."),this.rebuildPipeline()}get pipeline(){return this._pipeline}get composer(){return this._composer}get passes(){return this._passes}get isWebGL2(){return this._isWebGL2}get composerTarget(){return this._composer.renderTarget1}get composerTarget2(){return this._composer.renderTarget2}get renderSize(){return this._renderSize}get context(){return this._context}get webglRenderer(){return this._renderer}get useLegacyLights(){return this._renderer.useLegacyLights}set useLegacyLights(e){this._renderer.useLegacyLights=e,this._updated({change:"useLegacyLights",data:e}),this.resetShadows(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}get clock(){return this._composer.clock}blit(e,{source:t,viewport:i,material:n,clear:s=!0,respectColorSpace:a=!1,blending:o=gn,transparent:l=!0,opacity:c,blendAlpha:h}={}){const u=a?this._composer.copyPass2:this._composer.copyPass,{renderToScreen:d,material:p,uniforms:m,clear:A}=u;n&&(u.material=n);const g=u.material.transparent,y=e?e.viewport.clone():this._renderer.getViewport(new rt),_=e?e.scissor.clone():this._renderer.getScissor(new rt),v=e?e.scissorTest:this._renderer.getScissorTest(),b=this._renderer.autoClear,T=this._renderer.getRenderTarget(),E=u.material.blending,M=u.material.uniforms.opacity?.value??1,S=u.material.blendAlpha,w=u.material.blendSrc,C=u.material.blendDst,D=u.material.blendEquation;i&&(e?(e.viewport.copy(i),e.scissor.copy(i),e.scissorTest=!0):(this._renderer.setViewport(i),this._renderer.setScissor(i),this._renderer.setScissorTest(!0))),this._renderer.autoClear=!1,u.material.blending=l?o:xr,u.uniforms=u.material.uniforms,u.renderToScreen=!1,u.clear=s,u.material.transparent=l,u.material.needsUpdate=!0,u.material.uniforms.opacity&&c!==void 0&&(u.material.uniforms.opacity.value=c),h!==void 0&&(u.material.blending=ir,u.material.blendSrc=jl,u.material.blendDst=Wl,u.material.blendEquation=Sr,u.material.blendAlpha=h),this._renderer.renderWithModes({sceneRender:!0,opaqueRender:!0,shadowMapRender:!1,backgroundRender:!1,transparentRender:!0,transmissionRender:!1},()=>{u.render(this._renderer,e||null,{texture:t},0,!1)}),u.material.uniforms.opacity&&c!==void 0&&(u.material.uniforms.opacity.value=M),u.renderToScreen=d,u.clear=A,u.material.blending=E,u.material.blendSrc=w,u.material.blendDst=C,u.material.blendEquation=D,u.material.blendAlpha=S,u.material.transparent=g,u.material=p,u.uniforms=m,this._renderer.autoClear=b,i&&(e?(e.viewport.copy(y),e.scissor.copy(_),e.scissorTest=v):(this._renderer.setViewport(y),this._renderer.setScissor(_),this._renderer.setScissorTest(v))),this._renderer.setRenderTarget(T)}clearColor({r:e,g:t,b:i,a:n,target:s,depth:a=!0,stencil:o=!0,viewport:l}){const c=this._renderer.getClearColor(new se),h=this._renderer.getClearAlpha();this._renderer.setClearColor(new se(e??c.r,t??c.g,i??c.b),n??h);const u=this._renderer.getRenderTarget(),d=this._renderer.getActiveCubeFace(),p=this._renderer.getActiveMipmapLevel(),m=s?s.viewport.clone():this._renderer.getViewport(new rt),A=s?s.scissor.clone():this._renderer.getScissor(new rt),g=s?s.scissorTest:this._renderer.getScissorTest();l&&(s?(s.viewport.copy(l),s.scissor.copy(l),s.scissorTest=!0):(this._renderer.setViewport(l),this._renderer.setScissor(l),this._renderer.setScissorTest(!0))),this._renderer.setRenderTarget(s??null),this._renderer.clear(!0,a,o),s&&typeof s.clear=="function"?s.clear(this._renderer,!0,a,o):(this._renderer.setRenderTarget(s??null),this._renderer.clear(!0,a,o)),l&&(s?(s.viewport.copy(m),s.scissor.copy(A),s.scissorTest=g):(this._renderer.setViewport(m),this._renderer.setScissor(A),this._renderer.setScissorTest(g))),this._renderer.setRenderTarget(u,d,p),this._renderer.setClearColor(c,h)}_withResolvedTarget(e,t,i){if(e.width&&e.height)return;const n=e.textures?.[t]??e.texture;if(!n)throw new Error("RenderManager: target has no texture");const s=n.image?.width||n.source?.data?.width,a=n.image?.height||n.source?.data?.height,o=this.getTempTarget(s&&a?{size:{width:s,height:a},type:n.type}:{sizeMultiplier:1,type:n.type});this.blit(o,{source:n,clear:!0});const l=i(o);return this.releaseTempTarget(o),l}renderTargetToCanvas(e,t=0,i){const n=this._withResolvedTarget(e,t,l=>this.renderTargetToCanvas(l,0,i));if(n)return n;i=i??document.createElement("canvas");const s=e.textures?.[t]??e.texture;i.width=e.width,i.height=e.height;const a=i.getContext("2d");if(!a)throw new Error("Unable to get 2d context");const o=a.createImageData(i.width,i.height,{colorSpace:["display-p3","srgb"].includes(s.colorSpace)?s.colorSpace:void 0});if(s.type===$t||s.type===zt){const l=this.renderTargetToBuffer(e,t);Ev({data:l,width:i.width,height:i.height},s.colorSpace,o)}else this._renderer.readRenderTargetPixels(e,0,0,i.width,i.height,o.data,void 0,t);return a.putImageData(o,0,0),i}renderTargetToDataUrl(e,t="image/png",i=90,n=0){const s=e.textures?.[n]??e.texture,a=this.renderTargetToCanvas(e,n),o=(s.flipY?a:Yy(a)).toDataURL(t,i);return a.remove(),o}renderTargetToBuffer(e,t=0){const i=e.textures?.[t]??e.texture,n=i.type===$t?new Uint16Array(e.width*e.height*4):i.type===zt?new Float32Array(e.width*e.height*4):new Uint8Array(e.width*e.height*4);return this._renderer.readRenderTargetPixels(e,0,0,e.width,e.height,n,void 0,t),n}exportRenderTarget(e,t="auto",i=0){const n=this._withResolvedTarget(e,i,u=>this.exportRenderTarget(u,t,0));if(n)return n;const s=e,a=["image/x-exr"],o=s.textures?.[i]??s.texture;let l=o.type===$t||o.type===zt;t==="auto"&&(t=l?"image/x-exr":"image/png"),a.includes(t)||(l=!1);let c;if(l)t!=="image/x-exr"&&(console.warn("RenderManager: mimeType ",t," is not supported for HDR. Using EXR instead"),t="image/x-exr"),c=new i_().parse(this._renderer,s,{textureIndex:i}).buffer;else{const u=this.renderTargetToDataUrl(s,t==="auto"?void 0:t,90,i);c=Qy(u.split(",")[1]),t=u.split(";")[0].split(":")[1]}const h=new Blob([c],{type:t});return h.ext=t==="image/x-exr"?"exr":t.split("/")[1],h.__buffer=c,h}_updated(e){this.dispatchEvent({...e,type:"update"})}_createTargetClass(e,t,i){const n=this._processNewTarget,s=this.disposeTarget.bind(this);return new class extends e{constructor(o,...l){super(...l),this.renderManager=o,this.assetType="renderTarget",this.name="RenderTarget",this._ui_isPrimitive=!0,this.uuid=Ui();const h=l[l.length-1]?.colorSpace;this._initTexture(h)}get texture(){return this.textures[0]}set texture(o){this.textures[0]=o}_initTexture(o){const l=c=>{o!==void 0&&(c.colorSpace=o),c.userData||(c.userData={}),c._target=this,c.toJSON=()=>({isRenderTargetTexture:!0})};Array.isArray(this.textures)&&this.textures.length>1?this.textures.forEach(l):l(this.texture)}setSize(o,l,c){return super.setSize(Math.floor(o),Math.floor(l),c),this}clone(o=!0){if(this.isTemporary)throw"Cloning temporary render targets not supported";if(Array.isArray(this.texture))throw"Cloning multiple render targets not supported";const l=new this.constructor(this.renderManager);l.copy(this),l._initTexture((Array.isArray(this.texture)?this.texture[0]:this.texture)?.colorSpace);const c=l.texture;return Array.isArray(c)?c.forEach(h=>h.isRenderTargetTexture=!0):c.isRenderTargetTexture=!0,n(l,this.sizeMultiplier||1,o)}dispose(o=!1){o===!0?s(this,!0):super.dispose()}}(this,...t,i)}get displayCanvasScaling(){return console.error("displayCanvasScaling is deprecated, use renderScale instead"),this.renderScale}set displayCanvasScaling(e){console.error("displayCanvasScaling is deprecated, use renderScale instead"),this.renderScale=e}},f.RenderManager.POWER_PREFERENCE="high-performance",f.RenderManager.ShaderChunk=ot,f.RenderManager.ShaderLib=Di,zr([hl("Render Size")],f.RenderManager.prototype,"_renderSize",2),zr([Oe("Render Scale",[.1,8],.05)],f.RenderManager.prototype,"renderScale",1),zr([z(),Oi("Shadow Map Type",["BasicShadowMap","PCFShadowMap","PCFSoftShadowMap","VSMShadowMap"].map((r,e)=>({label:r,value:e})),{tags:["advanced"]}),Vt({obj:"shadowMap",key:"type",onChange:f.RenderManager.prototype._shadowMapTypeChanged})],f.RenderManager.prototype,"shadowMapType",2),zr([Vt({obj:"renderer",key:"shadowMap"})],f.RenderManager.prototype,"shadowMap",2),zr([Li(void 0,{label:"Passes",tags:["advanced"],order:1e3})],f.RenderManager.prototype,"_passes",2),zr([ae(),z()],f.RenderManager.prototype,"stableNoise",2),zr([ei(f.RenderManager.prototype.rebuildPipeline)],f.RenderManager.prototype,"autoBuildPipeline",2),zr([lt("Rebuild Pipeline",{sendArgs:!1,tags:["advanced"]})],f.RenderManager.prototype,"rebuildPipeline",1),zr([z()],f.RenderManager.prototype,"useLegacyLights",1),f.RenderManager=zr([Vc("RenderManager"),gt("Render Manager")],f.RenderManager);var rV=Object.defineProperty,aV=Object.getOwnPropertyDescriptor,I1=(r,e,t,i)=>{for(var n=i>1?void 0:i?aV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&rV(e,t,n),n};f.ViewerRenderManager=class extends f.RenderManager{constructor({rgbm:e=!0,msaa:t=!1,depthBuffer:i=!0,stencilBuffer:n=!1,...s}){super({...s,targetOptions:{samples:0,colorSpace:e?Gs:si,type:e?Wt:$t,depthBuffer:i,stencilBuffer:n,generateMipmaps:!1,minFilter:st}}),this.rgbm=e,this.msaa=t&&this.isWebGL2,this.depthBuffer=i,this.zPrepass=s.zPrepass||!1,this.maxHDRIntensity=s.maxHDRIntensity??(e?16:72);let a=!0;this._renderer.userData||(a=!1,this._renderer.userData={__isIWebGLRenderer:!0}),this._renderer.userData.renderTransmissionPass=!a,this.renderPass=new A0(this),this.screenPass=new f.ScreenPass(s.screenShader||""),this.registerPass(this.renderPass),this.registerPass(this.screenPass)}_gbufferUnpackExtensionChanged(e){this.dispatchEvent({type:"gbufferUnpackExtensionChanged",...e})}render(e,t){const i=this.screenPass.clipBackgroundForce;if(this.rgbm){const n=!e.background&&!e.backgroundColor;n!==i&&(this.screenPass.clipBackgroundForce=n)}super.render(e,t)}},f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES=4,I1([tt(f.ViewerRenderManager.prototype._gbufferUnpackExtensionChanged)],f.ViewerRenderManager.prototype,"gbufferUnpackExtension",2),f.ViewerRenderManager=I1([gt("Render Manager")],f.ViewerRenderManager);const eb=class eb extends pt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.fromJSON=void 0,this._lastFrameTime=0,this._lastPreFrameTime=0,this._updaters=[],this._timelineUpdaters=[],this.dependencies=[],this._fadeDisabled=!1,this.disableFrameFade=!0,this.autoIncrementTime=!0,this._postFrame=()=>{if(!this._viewer)return;if(this.isDisabled()||Object.keys(this._updaters).length<1){this._lastFrameTime=0,this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1);return}let t;if(this.autoIncrementTime){const i=Mn()/1e3;this._lastFrameTime<1&&(this._lastFrameTime=i-1/60),t=i-this._lastFrameTime,this._lastFrameTime=i;const n=this._viewer.getPlugin("Progressive")?.postFrameConvergedRecordingDelta();n&&n>0&&(t=n),n===0&&(t=0)}else{const i=this._viewer.timeline.time;t=i-this._lastFrameTime,this._lastFrameTime=i}if(t*=1e3,!(Math.abs(t)<=1e-4)&&(this._updaters.forEach(i=>{let n=t;i.time+n<0&&(n=-i.time),i.time+=n,Math.abs(n)>.001&&i.u(n)}),!this._fadeDisabled&&this.disableFrameFade)){const i=this._viewer.getPlugin("FrameFade");i&&(i.disable(this),this._fadeDisabled=!0)}},this._preFrame=()=>{if(!this._viewer)return;if(this.isDisabled()||Object.keys(this._timelineUpdaters).length<1){this._lastPreFrameTime=0;return}const t=this._viewer.timeline.time*1e3,i=t-this._lastPreFrameTime;this._lastPreFrameTime=t,!(Math.abs(i)<=1e-4)&&this._timelineUpdaters.forEach(n=>{let s=i;n.time!==t&&(s=t-n.time),n.time+s<0&&(s=-n.time),n.time+=s,Math.abs(s)>.001&&n.u(s)})},this.defaultDriver=t=>({start:()=>this._updaters.push({u:t,time:0}),stop:()=>{const i=this._updaters.findIndex(n=>n.u===t);i>=0&&this._updaters.splice(i,1)}}),this.timelineDriver=t=>({start:()=>this._timelineUpdaters.push({u:t,time:0}),stop:()=>{const i=this._timelineUpdaters.findIndex(n=>n.u===t);i>=0&&this._timelineUpdaters.splice(i,1)}}),this.animations={},this.enabled=e,this._postFrame=this._postFrame.bind(this)}onAdded(e){super.onAdded(e),e.addEventListener("postFrame",this._postFrame),e.addEventListener("preFrame",this._preFrame)}onRemove(e){e.removeEventListener("postFrame",this._postFrame),super.onRemove(e)}animate(e,t){const{target:i,key:n,...s}={...e};let a=s.from,o=s.to;if(i!==void 0){if(n===void 0)throw new Error("PopmotionPlugin - key must be defined when animating in target");n in i||(this._viewer?.console.warn("PopmotionPlugin - key not present in target, creating",n,i),i[n]=a??0);const c=s0(i,n),h=()=>i[n];s.lastOnUpdate=s.onUpdate,s.onUpdate=u=>{c(u),s.lastOnUpdate&&s.lastOnUpdate(u)},a===void 0&&(!Array.isArray(o)||o.length<2)&&(a=h())}const l=this.createAnimationResult(s);return l.promise=new Promise((c,h)=>{const u=()=>{try{s.onEnd&&s.onEnd()}catch(g){return h(g),!1}return!0},d=a??(Array.isArray(o)?o[0]:a);if(d===void 0){console.warn("from is undefined",s),c();return}const p=typeof d=="boolean";Array.isArray(o)&&o.length<2&&(o=o[0]);const m={...s,driver:s.driver||this.defaultDriver,to:o,from:a,onUpdate:g=>{s.onUpdate&&(p?s.onUpdate(g>=1):s.onUpdate(g))},onComplete:async()=>{try{s.onComplete&&await s.onComplete()}catch(g){if(!u())return;h(g);return}u()&&c()},onStop:async()=>{try{s.onStop&&await s.onStop()}catch(g){if(!u())return;h(g);return}c()}},A=t?t(m):n0(m);l._stop=A.stop,l.options=m}).then(()=>(delete this.animations[l.id],l.id)),l}async animateAsync(e,t){const i=this.animate(e);return t&&t.push(i),i.promise}animateNumber(e){let t=e.from??0;return this.animate({...e,from:t,to:e.to??1,onUpdate:i=>{const n=i-t;t=i,e.onUpdate&&e.onUpdate(i,n)}})}timeout(e,t){return this.animate({from:0,to:e,duration:e,...t})}async animateTargetAsync(e,t,i,n){const s=this.animate({...i,target:e,key:t});return n&&n.push(s),s.promise}animateTarget(e,t,i){return this.animate({...i,target:e,key:t})}animateCamera(e,t,i=!0,n){const s=i?iM(e,t):nM(e,t);let a=(n?.duration??1e3)*(t.duration??1);if(n?.normalizeDuration&&a>0){const o=e.getWorldPosition(new x),l=o.distanceTo(t.position)+e.target.distanceTo(t.target);if(l<.001){s.onComplete?.();const h=this.createAnimationResult();return h.promise=Promise.resolve(h.id).then(()=>(delete this.animations[h.id],h.id)),h}const c=Math.max(o.distanceTo(e.target),.1);a=Math.max(100,a*Math.min(1,l/c))}return this.animate({ease:Kc.linear,...s,...n,duration:a})}async animateCameraAsync(e,t,i=!0,n,s){const a=this.animateCamera(e,t,i,n);return s&&s.push(a),a.promise}createAnimationResult(e={}){const t=Ui();return this.animations[t]={id:t,options:e,stop:()=>this.stopAnimationResult(t),stopped:!1,_stop:()=>{},anims:[],promise:void 0}}stopAnimationResult(e){const t=this.animations[e];!t||t.stopped||(t._stop?typeof t._stop=="function"&&t._stop():console.warn("Animation not started"),t.anims?.forEach(i=>i.stop()),t.stopped=!0)}animateObject(e,t,i=!0,n,s){const{key:a,tar:o,onChange:l}=l0(e);let c=a;o&&c&&!(c in o)&&(console.error("PopmotionPlugin invalid key",c,o,e),c=void 0);const h=this.createAnimationResult(e.options);i&&(e.result=h),t=(t||0)+((s??e.delay)||0),h.anims=e.animSet?[...h.anims,this.animateSet(e.animSet,e.animSetParallel??!1,t,i,n)]:h.anims;const u=e.updater??[],d=!c||!o?{to:[0,1]}:{target:o,key:c,to:e.values,offset:e.offsets};return h.anims.push(this.animate({...d,driver:n,ease:typeof e.ease=="string"?Kc[e.ease]:e.ease,duration:e.duration,...e.options,canComplete:i,delay:t,onUpdate:p=>{e.options.onUpdate&&e.options.onUpdate(p),l&&l(),u.forEach(m=>m&&m())}},PN)),h.promise=Promise.all(h.anims.map(async p=>p.promise)).then(()=>(h.anims=[],delete this.animations[h.id],e.result===h&&(e.result=void 0),h.id)),h}animateSet(e,t=!1,i=0,n=!0,s){const a=this.createAnimationResult();if(t)a.anims=e.map(o=>this.animateObject(o,i,n,s));else{let o=i;for(const l of e){a.anims.push(this.animateObject(l,o,n,s));const{delay:c=0,duration:h=0,options:u}=l;o+=c+h+(h+(u.repeatDelay||0))*(u.repeat||0)}}return a.promise=Promise.all(a.anims.map(async o=>o.promise)).then(()=>(a.anims=[],delete this.animations[a.id],a.id)),a}};eb.PluginType="PopmotionPlugin";let Vr=eb;var oV=Object.defineProperty,lV=Object.getOwnPropertyDescriptor,Pn=(r,e,t,i)=>{for(var n=i>1?void 0:i?lV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&oV(e,t,n),n};f.InteractionPromptPlugin=class extends pt{constructor(e=!0){super(),this.animationRunning=!1,this.animationDuration=2e3,this.animationDistance=80,this.animationPauseDuration=6e3,this.rotationDistance=.3,this.yOffset=0,this.autoStart=!0,this.autoStartDelay=3e4,this.autoStop=!0,this.autoStartOnObjectLoad=!0,this.autoStartOnObjectLoadDelay=3e3,this.currentTime=0,this.lastActionTime=1/0,this.pointerIcon=`<svg xmlns="http://www.w3.org/2000/svg" style="transform: translate(-50%, -25%);" xmlns:xlink="http://www.w3.org/1999/xlink" width="25" height="36">
    <defs>
        <path id="A" d="M.001.232h24.997V36H.001z"></path>
    </defs>
    <g transform="translate(-11 -4)" fill="none" fill-rule="evenodd">
        <path fill-opacity="0" fill="#fff" d="M0 0h44v44H0z"></path>
        <g transform="translate(11 3)">
            <path d="M8.733 11.165c.04-1.108.766-2.027 1.743-2.307a2.54 2.54 0 0 1 .628-.089c.16 0 .314.017.463.044 1.088.2 1.9 1.092 1.9 2.16v8.88h1.26c2.943-1.39 5-4.45 5-8.025a9.01 9.01 0 0 0-1.9-5.56l-.43-.5c-.765-.838-1.683-1.522-2.712-2-1.057-.49-2.226-.77-3.46-.77s-2.4.278-3.46.77c-1.03.478-1.947 1.162-2.71 2l-.43.5a9.01 9.01 0 0 0-1.9 5.56 9.04 9.04 0 0 0 .094 1.305c.03.21.088.41.13.617l.136.624c.083.286.196.56.305.832l.124.333a8.78 8.78 0 0 0 .509.953l.065.122a8.69 8.69 0 0 0 3.521 3.191l1.11.537v-9.178z" fill-opacity=".5" fill="#e4e4e4"></path>
            <path d="M22.94 26.218l-2.76 7.74c-.172.485-.676.8-1.253.8H12.24c-1.606 0-3.092-.68-3.98-1.82-1.592-2.048-3.647-3.822-6.11-5.27-.095-.055-.15-.137-.152-.23-.004-.1.046-.196.193-.297.56-.393 1.234-.6 1.926-.6a3.43 3.43 0 0 1 .691.069l4.922.994V10.972c0-.663.615-1.203 1.37-1.203s1.373.54 1.373 1.203v9.882h2.953c.273 0 .533.073.757.21l6.257 3.874c.027.017.045.042.07.06.41.296.586.77.426 1.22M4.1 16.614c-.024-.04-.042-.083-.065-.122a8.69 8.69 0 0 1-.509-.953c-.048-.107-.08-.223-.124-.333l-.305-.832c-.058-.202-.09-.416-.136-.624l-.13-.617a9.03 9.03 0 0 1-.094-1.305c0-2.107.714-4.04 1.9-5.56l.43-.5c.764-.84 1.682-1.523 2.71-2 1.058-.49 2.226-.77 3.46-.77s2.402.28 3.46.77c1.03.477 1.947 1.16 2.712 2l.428.5a9 9 0 0 1 1.901 5.559c0 3.577-2.056 6.636-5 8.026h-1.26v-8.882c0-1.067-.822-1.96-1.9-2.16-.15-.028-.304-.044-.463-.044-.22 0-.427.037-.628.09-.977.28-1.703 1.198-1.743 2.306v9.178l-1.11-.537C6.18 19.098 4.96 18 4.1 16.614M22.97 24.09l-6.256-3.874c-.102-.063-.218-.098-.33-.144 2.683-1.8 4.354-4.855 4.354-8.243 0-.486-.037-.964-.104-1.43a9.97 9.97 0 0 0-1.57-4.128l-.295-.408-.066-.092a10.05 10.05 0 0 0-.949-1.078c-.342-.334-.708-.643-1.094-.922-1.155-.834-2.492-1.412-3.94-1.65l-.732-.088-.748-.03a9.29 9.29 0 0 0-1.482.119c-1.447.238-2.786.816-3.94 1.65a9.33 9.33 0 0 0-.813.686 9.59 9.59 0 0 0-.845.877l-.385.437-.36.5-.288.468-.418.778-.04.09c-.593 1.28-.93 2.71-.93 4.222 0 3.832 2.182 7.342 5.56 8.938l1.437.68v4.946L5 25.64a4.44 4.44 0 0 0-.888-.086c-.017 0-.034.003-.05.003-.252.004-.503.033-.75.08a5.08 5.08 0 0 0-.237.056c-.193.046-.382.107-.568.18-.075.03-.15.057-.225.1-.25.114-.494.244-.723.405a1.31 1.31 0 0 0-.566 1.122 1.28 1.28 0 0 0 .645 1.051C4 29.925 5.96 31.614 7.473 33.563a5.06 5.06 0 0 0 .434.491c1.086 1.082 2.656 1.713 4.326 1.715h6.697c.748-.001 1.43-.333 1.858-.872.142-.18.256-.38.336-.602l2.757-7.74c.094-.26.13-.53.112-.794s-.088-.52-.203-.76a2.19 2.19 0 0 0-.821-.91" fill-opacity=".6" fill="#000"></path>
            <path d="M22.444 24.94l-6.257-3.874a1.45 1.45 0 0 0-.757-.211h-2.953v-9.88c0-.663-.616-1.203-1.373-1.203s-1.37.54-1.37 1.203v16.643l-4.922-.994a3.44 3.44 0 0 0-.692-.069 3.35 3.35 0 0 0-1.925.598c-.147.102-.198.198-.194.298.004.094.058.176.153.23 2.462 1.448 4.517 3.22 6.11 5.27.887 1.14 2.373 1.82 3.98 1.82h6.686c.577 0 1.08-.326 1.253-.8l2.76-7.74c.16-.448-.017-.923-.426-1.22-.025-.02-.043-.043-.07-.06z" fill="#fff"></path>
            <g transform="translate(0 .769)">
                <mask id="B" fill="#fff">
                    <use xlink:href="#A"></use>
                </mask>
                <path d="M23.993 24.992a1.96 1.96 0 0 1-.111.794l-2.758 7.74c-.08.22-.194.423-.336.602-.427.54-1.11.87-1.857.872h-6.698c-1.67-.002-3.24-.633-4.326-1.715-.154-.154-.3-.318-.434-.49C5.96 30.846 4 29.157 1.646 27.773c-.385-.225-.626-.618-.645-1.05a1.31 1.31 0 0 1 .566-1.122 4.56 4.56 0 0 1 .723-.405l.225-.1a4.3 4.3 0 0 1 .568-.18l.237-.056c.248-.046.5-.075.75-.08.018 0 .034-.003.05-.003.303-.001.597.027.89.086l3.722.752V20.68l-1.436-.68c-3.377-1.596-5.56-5.106-5.56-8.938 0-1.51.336-2.94.93-4.222.015-.03.025-.06.04-.09.127-.267.268-.525.418-.778.093-.16.186-.316.288-.468.063-.095.133-.186.2-.277L3.773 5c.118-.155.26-.29.385-.437.266-.3.544-.604.845-.877a9.33 9.33 0 0 1 .813-.686C6.97 2.167 8.31 1.59 9.757 1.35a9.27 9.27 0 0 1 1.481-.119 8.82 8.82 0 0 1 .748.031c.247.02.49.05.733.088 1.448.238 2.786.816 3.94 1.65.387.28.752.588 1.094.922a9.94 9.94 0 0 1 .949 1.078l.066.092c.102.133.203.268.295.408a9.97 9.97 0 0 1 1.571 4.128c.066.467.103.945.103 1.43 0 3.388-1.67 6.453-4.353 8.243.11.046.227.08.33.144l6.256 3.874c.37.23.645.55.82.9.115.24.185.498.203.76m.697-1.195c-.265-.55-.677-1.007-1.194-1.326l-5.323-3.297c2.255-2.037 3.564-4.97 3.564-8.114 0-2.19-.637-4.304-1.84-6.114-.126-.188-.26-.37-.4-.552-.645-.848-1.402-1.6-2.252-2.204C15.472.91 13.393.232 11.238.232A10.21 10.21 0 0 0 5.23 2.19c-.848.614-1.606 1.356-2.253 2.205-.136.18-.272.363-.398.55C1.374 6.756.737 8.87.737 11.06c0 4.218 2.407 8.08 6.133 9.842l.863.41v3.092l-2.525-.51c-.356-.07-.717-.106-1.076-.106a5.45 5.45 0 0 0-3.14.996c-.653.46-1.022 1.202-.99 1.983a2.28 2.28 0 0 0 1.138 1.872c2.24 1.318 4.106 2.923 5.543 4.772 1.26 1.62 3.333 2.59 5.55 2.592h6.698c1.42-.001 2.68-.86 3.134-2.138l2.76-7.74c.272-.757.224-1.584-.134-2.325" fill-opacity=".05" fill="#000" mask="url(#B)"></path>
            </g>
        </g>
    </g>
</svg>`,this._mainCameraUpdate=t=>{this.isDisabled()||(t.change==="deserialize"&&this.animationRunning?(this.stopAnimation({reset:!1}),this.startAnimation()):this._startedOnce&&(this.lastActionTime=Mn()))},this._startedOnce=!1,this._addSceneObject=()=>{this.autoStartOnObjectLoad&&!this._startedOnce&&(this.lastActionTime=Mn()-this.autoStartDelay+this.autoStartOnObjectLoadDelay)},this.onlyOnOrbitControls=!0,this._orbitWarning=!1,this.startAnimation=()=>{if(!(!this._viewer||!this.cursorEl||this.isDisabled())){if(this._viewer.scene.mainCamera.controls?.type!=="OrbitControls"&&this.onlyOnOrbitControls){this._orbitWarning||console.warn("InteractionPromptPlugin requires OrbitControls, to run anyway, set onlyOnOrbitControls to false"),this._orbitWarning=!0;return}this._viewer.scene.modelRoot.children.length!==0&&(this.currentSphericalPosition=new pa().setFromVector3(new x().subVectors(this._viewer.scene.mainCamera.position,this._viewer.scene.mainCamera.target)),this.cursorEl.style.opacity="1",this.currentTime=0,this.animationRunning=!0,this._startedOnce=!0,this._viewer.scene.mainCamera.setInteractions(!1,f.InteractionPromptPlugin.PluginType))}},this.stopAnimation=async({reset:t=!0}={})=>{if(!(!this._viewer||!this.cursorEl))return this.animationRunning=!1,this.cursorEl.style.opacity="0",this.currentSphericalPosition&&t&&(this._viewer.scene.mainCamera.position.setFromSpherical(this.currentSphericalPosition).add(this._viewer.scene.mainCamera.target),this._viewer.scene.mainCamera.setDirty(),this.currentSphericalPosition=void 0),this._viewer.scene.mainCamera.setInteractions(!0,f.InteractionPromptPlugin.PluginType),this._viewer.doOnce("postFrame")},this._pointerDown=()=>{this.isDisabled()||(this.autoStop&&this.stopAnimation({reset:!1}),this.lastActionTime=Mn())},this._x=0,this._preFrame=async t=>{if(!this._viewer||!this.cursorEl||(this.isDisabled()&&this.animationRunning&&this.stopAnimation(),this.isDisabled())||(!this.animationRunning&&this.autoStart&&this.lastActionTime+this.autoStartDelay<Mn()&&this.startAnimation(),!this.animationRunning))return;if(this.currentTime<=this.animationDuration){this.cursorEl.style.opacity="1";const a=this.currentTime/this.animationDuration;this._x=Math.sin(Math.PI*2*a),(a<.25||a>.75)&&(this._x*=this._x*Math.sign(this._x))}else this.cursorEl.style.opacity="0",this._x=0;if(this.currentTime<=this.animationDuration+50){const a=this.currentSphericalPosition.clone();a.theta+=this._x*this.rotationDistance,this._viewer.scene.mainCamera.position.setFromSpherical(a).add(this._viewer.scene.mainCamera.target),this._viewer.scene.mainCamera.setDirty()}const i=this._viewer.container.getBoundingClientRect(),n=i.width/2+-this._x*Math.min(this.animationDistance,i.width/4),s=i.height/2+this.yOffset*i.height/2;this.cursorEl.style.transform=`translate(${Math.floor(n)}px, ${Math.floor(s)}px)`,this.currentTime+=t.deltaTime,this.currentTime>this.animationDuration+this.animationPauseDuration&&(this.currentTime=0)},this.enabled=e}onAdded(e){super.onAdded(e);{qn(e.plugins,"InteractionPointerPlugin")&&delete e.plugins.InteractionPointerPlugin;const t=this;Object.defineProperty(e.plugins,"InteractionPointerPlugin",{get(){return console.warn("InteractionPromptPlugin: PluginType renamed from InteractionPointerPlugin to InteractionPromptPlugin. Please update your code/vjson."),t},configurable:!0})}this.lastActionTime=1/0,e.addEventListener("preFrame",this._preFrame),e.container.addEventListener("pointerdown",this._pointerDown,!0),e.container.addEventListener("wheel",this._pointerDown,!0),e.scene.addEventListener("addSceneObject",this._addSceneObject),e.scene.addEventListener("mainCameraUpdate",this._mainCameraUpdate),this._initializeCursor()}onRemove(e){return this.stopAnimation(),e.removeEventListener("preFrame",this._preFrame),e.container.removeEventListener("pointerdown",this._pointerDown,!0),e.container.removeEventListener("wheel",this._pointerDown,!0),e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.scene.removeEventListener("mainCameraUpdate",this._mainCameraUpdate),this.cursorEl&&this.cursorEl.remove(),super.onRemove(e)}_pointerIconChanged(){this.cursorEl&&(this.cursorEl.innerHTML=this.pointerIcon)}_initializeCursor(){this.cursorEl=document.createElement("div"),this.cursorEl.style.position="absolute",this.cursorEl.style.top="0",this.cursorEl.style.left="0",this.cursorEl.style.width="10px",this.cursorEl.style.height="10px",this.cursorEl.style.opacity="0",this._pointerIconChanged(),this._viewer.container.appendChild(this.cursorEl)}},f.InteractionPromptPlugin.PluginType="InteractionPromptPlugin",Pn([z(),ae()],f.InteractionPromptPlugin.prototype,"enabled",2),Pn([z(),Fe()],f.InteractionPromptPlugin.prototype,"animationDuration",2),Pn([z(),Fe()],f.InteractionPromptPlugin.prototype,"animationDistance",2),Pn([z(),Fe()],f.InteractionPromptPlugin.prototype,"animationPauseDuration",2),Pn([z(),Fe()],f.InteractionPromptPlugin.prototype,"rotationDistance",2),Pn([z(),Fe()],f.InteractionPromptPlugin.prototype,"yOffset",2),Pn([z(),ae()],f.InteractionPromptPlugin.prototype,"autoStart",2),Pn([z(),Fe()],f.InteractionPromptPlugin.prototype,"autoStartDelay",2),Pn([z(),ae()],f.InteractionPromptPlugin.prototype,"autoStop",2),Pn([z(),ae()],f.InteractionPromptPlugin.prototype,"autoStartOnObjectLoad",2),Pn([z(),ae()],f.InteractionPromptPlugin.prototype,"autoStartOnObjectLoadDelay",2),Pn([hl()],f.InteractionPromptPlugin.prototype,"currentTime",2),Pn([hl()],f.InteractionPromptPlugin.prototype,"lastActionTime",2),Pn([de(f.InteractionPromptPlugin.prototype._pointerIconChanged)],f.InteractionPromptPlugin.prototype,"pointerIcon",2),Pn([z()],f.InteractionPromptPlugin.prototype,"onlyOnOrbitControls",2),Pn([lt()],f.InteractionPromptPlugin.prototype,"startAnimation",2),Pn([lt()],f.InteractionPromptPlugin.prototype,"stopAnimation",2),f.InteractionPromptPlugin=Pn([gt("Interaction Prompt")],f.InteractionPromptPlugin);var cV=Object.defineProperty,hV=Object.getOwnPropertyDescriptor,Os=(r,e,t,i)=>{for(var n=i>1?void 0:i?hV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&cV(e,t,n),n};const cs=(Wr=class extends pt{constructor(e={}){super(),this.enabled=!0,this._cameraViews=[],this.viewLooping=!1,this.viewPauseTime=200,this.animEase="easeInOutSine",this.animDuration=1e3,this.interpolateMode="spherical",this.rotationOffset=.25,this._animating=!1,this.dependencies=[Vr],this.focusNext=(t=!0)=>{if(this._animating||this._cameraViews.length<2)return;let i=this._cameraViews.findIndex(n=>n===this._currentView);i<0&&(i=-1),i=i+1,t?i=i%this._cameraViews.length:i=Math.min(i,this._cameraViews.length-1),this.animateToView(i)},this.focusPrevious=(t=!0)=>{if(this._animating||this._cameraViews.length<2||!this._currentView)return;let i=this._cameraViews.findIndex(n=>n===this._currentView);i<0&&(i=0),i=i-1,t?i=(i+this._cameraViews.length)%this._cameraViews.length:i=Math.max(i,0),this.animateToView(i)},this._popAnimations=[],this.uiConfig={type:"folder",label:"Camera Views",children:[()=>[...this._cameraViews.map(t=>t.uiConfig)],...vi(this)||[]]},this._viewQueue=[],this._animationLooping=!1,this._infiniteLooping=!0,this._viewSetView=({view:t,camera:i})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}this.setView(t,i)},this._viewUpdateView=({view:t,camera:i})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}const n=t.name;this.getView(i,t.isWorldSpace??!0,t),t.name=n},this._viewDeleteView=({view:t})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}this.deleteView(t)},this._viewAnimateView=async({view:t,camera:i,duration:n,easing:s,throwOnStop:a})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}return this.animateToView(t,n||this.animDuration,s||this.animEase,i,a)},this._viewUpdated=async t=>{this._cameraViews.includes(t.target)&&(this.dispatchEvent({type:"viewUpdate",view:t.target}),this.setDirty({key:"cameraViews",change:"viewUpdate"}))},this._lastAnimTime=-1,this.addCurrentView=this.addCurrentView.bind(this),this.resetToFirstView=this.resetToFirstView.bind(this),this.animateAllViews=this.animateAllViews.bind(this),this._postFrame=this._postFrame.bind(this),this.setDirty=this.setDirty.bind(this),this.animDuration=e.duration??this.animDuration,this.animEase=e.ease??this.animEase,this.interpolateMode=e.interpolateMode??this.interpolateMode}get cameraViews(){return this._cameraViews}get camViews(){return this._cameraViews}get animating(){return this._animating}onAdded(e){super.onAdded(e),e.addEventListener("preFrame",t=>{}),e.addEventListener("postFrame",this._postFrame)}onRemove(e){return e.removeEventListener("postFrame",this._postFrame),super.onRemove(e)}async resetToFirstView(e=100){this.isDisabled()||(this._currentView=void 0,await this.animateToView(0,e),await jn(2))}async addCurrentView(){if(this.isDisabled())return;const e=this._viewer?.scene.mainCamera;if(!e)return;const t=this.getView(e);return this.addView(t),t.name="View "+this._cameraViews.length,t}addView(e,t=!1){e.addEventListener("setView",this._viewSetView),e.addEventListener("updateView",this._viewUpdateView),e.addEventListener("deleteView",this._viewDeleteView),e.addEventListener("animateView",this._viewAnimateView),e.addEventListener("update",this._viewUpdated);const i=this._cameraViews.includes(e);(!i||t)&&(i||this._cameraViews.push(e),this.setDirty({key:"cameraViews",change:"viewAdd"}),this.dispatchEvent({type:"viewAdd",view:e}))}deleteView(e,t=!1){const i=this._cameraViews.indexOf(e);e.removeEventListener("setView",this._viewSetView),e.removeEventListener("updateView",this._viewUpdateView),e.removeEventListener("deleteView",this._viewDeleteView),e.removeEventListener("animateView",this._viewAnimateView),e.removeEventListener("update",this._viewUpdated),(i>=0||t)&&(i>=0&&this._cameraViews.splice(i,1),this.setDirty({key:"cameraViews",change:"viewDelete"}),this.dispatchEvent({type:"viewDelete",view:e}))}getView(e,t=!0,i){return e=e||this._viewer?.scene.mainCamera,e?e.getView(t,i):i??new f.CameraView}setView(e,t){t=t||this._viewer?.scene.mainCamera,t&&t.setView(e)}async animateToView(e,t,i,n,s=!1,a){if(n=n||this._viewer?.scene.mainCamera,!n)return;if(this._animating){this._popAnimations.forEach(d=>d?.stop&&d.stop()),this._popAnimations=[];let u=0;for(;this._animating&&(await jn(100),!(u++>20)););if(this._animating){console.warn("Unable to stop all animations, maybe because of viewLooping?");return}}const o=typeof e=="number"?this._cameraViews[e]:typeof e=="string"?this._cameraViews.find(u=>u.name===e):e;if(!o){this._viewer?.console.warn("Invalid view",e);return}a=a??t===void 0;const l=this._viewer?.getPlugin(f.InteractionPromptPlugin);l&&l.animationRunning&&await l.stopAnimation({reset:!0}),this._currentView=o,this._animating=!0,n.setInteractions&&n.setInteractions(!1,Wr.PluginType),n.userData.autoLookAtTarget||console.warn("CameraViewPlugin: camera autoLookAtTarget is disabled, camera look at might not be correct during animation"),this.dispatchEvent({type:"startViewChange",view:o});const c=this._viewer?.getPlugin(Vr);if(!c)throw new Error("PopmotionPlugin not found");const h=typeof i=="function"?i:Kc[i||this.animEase];this._popAnimations=[],await c.animateCameraAsync(n,o,this.interpolateMode==="spherical",{ease:h,duration:t,normalizeDuration:a},this._popAnimations).catch(u=>{if(s)throw u}),this._viewer?.scene.mainCamera.setInteractions(!0,Wr.PluginType),this._animating=!1,this._viewer?.setDirty(),this.dispatchEvent({type:"viewChange",view:o}),await jn(10)}async animateAllViews(){if(!this.isDisabled()&&!(this.viewLooping||this._cameraViews.length<2)){for(;this._viewQueue.length>0;)this._viewQueue.pop();this._viewQueue.push(...this._cameraViews),this._viewQueue.push(this._viewQueue.shift()),this._infiniteLooping=!1,await this._animationLoop(),this._infiniteLooping=!0}}async stopAllAnimations(){for(this.viewLooping=!1,this._popAnimations.forEach(e=>e?.stop?.()),this._popAnimations=[];this._animating||this._animationLooping;)await jn(100)}fromJSON(e,t){return this._cameraViews.forEach(i=>this.deleteView(i)),super.fromJSON(e,t)?(this._cameraViews.forEach(i=>this.addView(i,!0)),this.uiConfig?.uiRefresh?.(),this):null}setDirty(e){this.uiConfig?.uiRefresh?.(!1,"postFrame"),this.dispatchEvent({...e,type:"update"})}async animateToObject(e,t=4,i,n,s={min:.5,max:5}){if(!this._viewer)return;const a=new In().expandByObject(e||this._viewer.scene.modelRoot,!1,!0),o=a.getCenter(new x),c=a.getSize(new x).length()/2;await this.animateToTarget(Math.min(s.max,Math.max(s.min,c*t)),o,i,n)}_resolveSelectedObjects(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap(t=>t?.isTexture?[...t.appliedObjects?.values()||[]]:t).flatMap(t=>t?.isMaterial?[...t.appliedMeshes?.values()||[]]:t?.isBufferGeometry?[...t.appliedMeshes?.values()||[]]:t).filter(Boolean)}async animateToFitObject(e,t=1.5,i,n,s={min:.5,max:50}){if(!this._viewer)return;const a=this._resolveSelectedObjects(e),o=a.length?a:[this._viewer.scene.modelRoot];if(i===0){this._viewer.scene.mainCamera.fitObject(o,t,s);return}const l=new In().expandByObject(o[0],!1,!0);for(let d=1;d<o.length;d++)l.expandByObject(o[d],!1,!0);const c=xm(this._viewer.scene.mainCamera,l),h=l.getCenter(new x);l.getSize(new x).lengthSq()<=0&&o[0].getWorldPosition(h),await this.animateToTarget(Math.min(s.max,Math.max(s.min,c*t)),h,i,n)}async animateToTarget(e,t,i,n){const s=this.getView();s.target.copy(t);const a=new x().subVectors(s.target,s.position).normalize();if(s.position.copy(a.multiplyScalar(-e).add(s.target)),i===0){this.setView(s),this._viewer?.setDirty();return}await this.animateToView(s,i,n,void 0,!1,!0)}get animationLooping(){return this._animationLooping}async _animationLoop(){if(!this._animationLooping){for(this._animationLooping=!0;(this.viewLooping||!this._infiniteLooping)&&!(this.isDisabled()||this._cameraViews.length<1);){if(this._viewQueue.length===0)if(this._infiniteLooping)this._viewQueue.push(...this._cameraViews);else break;await this.animateToView(this._viewQueue.shift()),await jn(2+this.viewPauseTime)}this._animationLooping=!1}}getCurrentCameraView(e,t=!0){return this.getView(e,t)}setCurrentCameraView(e){return this.setView(e)}async focusView(e){return this.animateToView(e)}_postFrame(){if(!this.enabled||!this._viewer)return;const e=this._viewer.scene.mainCamera;if(!e)return;if(!this._viewer.timeline.shouldRun()||!this._cameraViews.length){e.setInteractions(!0,Wr.PluginType+"-postFrame"),this._lastAnimTime=-1;return}e.setInteractions(!1,Wr.PluginType+"-postFrame");const t=this._viewer.timeline.time;if(t==this._lastAnimTime)return;this._lastAnimTime=t;const i=[],n=this.animDuration||1e3,s=this.viewPauseTime||0,a=this._cameraViews;let o=0;for(let A=0;A<a.length;A++){const g=a[A],y=Math.max(2,g.duration*n)/1e3;i.push({time:o,index:A,duration:y}),o+=y+s/1e3}const l=i.sort((A,g)=>-A.time+g.time).find(A=>A.time<=t);if(!l)return;const c=l.index,h=l.time,u=l.duration??.5,d=u<1e-6?1:(t-h)/u;if(d>1)return;const{getPosition:p,getTarget:m}=IM(this.camViews);return p(d,c,e.position),m(d,c,e.target),e.setDirty(),!0}},Wr.PluginType="CameraViews",Wr);Os([z("cameraViews")],cs.prototype,"_cameraViews",2),Os([de(cs.prototype._animationLoop),z(),ae("Loop All Views")],cs.prototype,"viewLooping",2),Os([tt("setDirty"),z(),Fe("View Pause Time")],cs.prototype,"viewPauseTime",2),Os([tt("setDirty"),z(),Oi("Ease",Object.keys(Kc).map(r=>({label:r})))],cs.prototype,"animEase",2),Os([tt("setDirty"),z(),Oe("Duration",[10,1e4],10)],cs.prototype,"animDuration",2),Os([tt("setDirty"),z(),Oi("Interpolation",["spherical","linear"].map(r=>({label:r,value:r.split(" ")[0]})))],cs.prototype,"interpolateMode",2),Os([z()],cs.prototype,"rotationOffset",2),Os([lt("Reset To First View",{sendArgs:!1})],cs.prototype,"resetToFirstView",1),Os([lt("Add Current View")],cs.prototype,"addCurrentView",1),Os([lt("Focus Next",{sendArgs:!1})],cs.prototype,"focusNext",2),Os([lt("Focus Previous",{sendArgs:!1})],cs.prototype,"focusPrevious",2),Os([lt("Animate All Views")],cs.prototype,"animateAllViews",1),Os([lt("Stop All Animations")],cs.prototype,"stopAllAnimations",1);let n_=cs;var uV=Object.defineProperty,dV=Object.getOwnPropertyDescriptor,_o=(r,e,t,i)=>{for(var n=i>1?void 0:i?dV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&uV(e,t,n),n};f.DropzonePlugin=class extends pt{constructor(e){super(),this.enabled=!0,this._allowedExtensions=void 0,this.autoImport=!0,this.autoAdd=!0,this.importOptions={autoImportZipContents:!0,forceImporterReprocess:!1,useMeshLines:Ml.UseMeshLines,createUniqueNames:Ml.CreateUniqueNames},this.addOptions={autoCenter:!0,importConfig:!0,autoScale:!0,autoScaleRadius:2,centerGeometries:!1,centerGeometriesKeepPosition:!0,license:"",clearSceneObjects:!1,disposeSceneObjects:!1,autoSetBackground:!1,autoSetEnvironment:!0},e&&(this._domElement=e.domElement,this.allowedExtensions=e.allowedExtensions,this.autoImport=e.autoImport??this.autoImport,this.autoAdd=e.autoAdd??this.autoAdd,this.importOptions={...this.importOptions,...e.importOptions},this.addOptions={...this.addOptions,...e.addOptions})}get allowedExtensions(){return this._allowedExtensions}set allowedExtensions(e){this._allowedExtensions=e,this._inputEl&&(this._inputEl.accept=e?e.map(t=>"."+t).join(", "):"")}promptForFile(){this.isDisabled()||(this.allowedExtensions=this._allowedExtensions,this._inputEl?.click())}async promptForUrl(){if(this.isDisabled()||!this._viewer)return;const e=await this._viewer.dialog.prompt("Enter URL: Enter a public URL for a 3d file with extension","",!0);!e||!e.length||await this.load(e,{},!0)}async load(e,t,i=!1){if(!this._viewer){console.warn("DropzonePlugin: viewer not set");return}if(this.autoImport){const n=this._viewer.assetManager,s=Fu(e);if(this._allowedExtensions&&!this._allowedExtensions.includes(s)){i&&await this._viewer.dialog.alert(`DropzonePlugin: file extension ${s} not allowed`);return}const o=[...await n.importer.import(e,{...this.importOptions,...t??{}})??[]].flat(2).filter(l=>!!l)??[];return this.autoAdd?await n.loadImported(o,{...this.addOptions,...t??{}}):o}else i&&await this._viewer.dialog.alert("DropzonePlugin: autoImport is disabled, file was not imported")}onAdded(e){super.onAdded(e),this._inputEl=document.createElement("input"),this._inputEl.type="file",this._domElement||(this._domElement=e.canvas),this._dropzone=new Zp(this._domElement,this._inputEl,{drop:this._onFileDrop.bind(this)}),this.allowedExtensions=this._allowedExtensions}onRemove(e){this._dropzone?.destroy(),this._dropzone=void 0,this._inputEl=void 0,super.onRemove(e)}async _onFileDrop({files:e,nativeEvent:t}){if(!e||this.isDisabled())return;const i=this._viewer;if(!i)return;if(this._allowedExtensions!==void 0)for(const o of e.keys())this._allowedExtensions.includes(o.split(".").pop()?.toLowerCase()??"")||e.delete(o);if(e.size<1)return;const n=i.assetManager;let s,a;if(this.autoImport&&(s=await n.importer.importFiles(e,{allowedExtensions:this.allowedExtensions,...this.importOptions}),this.autoAdd)){const o=[...s?.values()??[]].flat(2).filter(l=>!!l)??[];a=await n.loadImported(o,{...this.addOptions})}this.dispatchEvent({type:"drop",files:e,imported:s,assets:a,nativeEvent:t})}},f.DropzonePlugin.PluginType="Dropzone",f.DropzonePlugin.OldPluginType="DropzonePlugin",_o([ae(),z()],f.DropzonePlugin.prototype,"enabled",2),_o([z()],f.DropzonePlugin.prototype,"autoImport",2),_o([ae(),z()],f.DropzonePlugin.prototype,"autoAdd",2),_o([Li(),z()],f.DropzonePlugin.prototype,"importOptions",2),_o([Li(),z()],f.DropzonePlugin.prototype,"addOptions",2),_o([lt("Select Local files")],f.DropzonePlugin.prototype,"promptForFile",1),_o([lt("Import from URL")],f.DropzonePlugin.prototype,"promptForUrl",1),f.DropzonePlugin=_o([gt("Dropzone")],f.DropzonePlugin);const fV=`
#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )
vec3 Uncharted2ToneMapping(vec3 color){color*=toneMappingExposure;return saturate(Uncharted2Helper(color)/Uncharted2Helper(vec3(1.0)));}vec3 CustomToneMapping(vec3 color){return Uncharted2ToneMapping(color);}`,pV=`int getToneMapBit(in int number){
#ifdef WebGL2Context
return(number/2)% 2;
#else
return int(mod(floor(float(number)/2.),2.));
#endif
}vec3 TonemappingSaturation(vec3 rgb){const vec3 W=vec3(0.2125,0.7154,0.0721);vec3 intensity=vec3(dot(rgb,W));return mix(intensity,rgb,toneMappingSaturation);}vec3 TonemappingContrast(vec3 color){return(color-vec3(0.5))*toneMappingContrast+vec3(0.5);}vec4 ToneMapping(in vec4 color){vec4 outColor=color;
#if defined( TONE_MAPPING )
outColor.rgb=toneMapping(outColor.rgb);outColor.rgb=TonemappingContrast(outColor.rgb);outColor.rgb=TonemappingSaturation(outColor.rgb);
#endif
return outColor;}`,mV=`bool doTonemap=true;
#ifdef HAS_GBUFFER
#ifdef GBUFFER_HAS_FLAGS
doTonemap=getToneMapBit(getGBufferFlags(vUv).a)>0;
#endif
#if TONEMAP_BACKGROUND < 1
if(isBackground)doTonemap=false;
#endif
#endif
if(doTonemap)diffuseColor=ToneMapping(diffuseColor);`;var gV=Object.defineProperty,P1=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&gV(e,t,n),n};const yg=class extends pt{constructor(){super(),this.enabled=!0,this._beforeRender=this._beforeRender.bind(this)}_beforeRender(e,t,i){return this._pass?(this._pass.enabled=!this.isDisabled(),this._pass.enabled):!1}onAdded(e){super.onAdded(e),this._pass=this._createPass(),this._pass.onDirty?.push(e.setDirty),this._pass.beforeRender=Zx(this._beforeRender,this._pass.beforeRender),e.renderManager.registerPass(this._pass)}onRemove(e){this._pass&&(e.renderManager.unregisterPass(this._pass),this._pass.dispose&&this._pass.dispose()),this._pass=void 0,super.onRemove(e)}get pass(){return this._pass}toJSON(e){return super.toJSON(e)}fromJSON(e,t){return super.fromJSON(e,t)}setDirty(){this._pass&&(this._pass.enabled=!this.isDisabled()),this._viewer?.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",100)}};P1([z(),ae("Enabled"),de(yg.prototype.setDirty)],yg.prototype,"enabled"),P1([z("pass")],yg.prototype,"_pass");let Tl=yg;const D1=`#ifndef UNPACK_GBUFFER_SNIPPET
#define UNPACK_GBUFFER_SNIPPET
uniform sampler2D tNormalDepth;float unpack16(vec2 value){return value.x+value.y/255.0;}vec3 unpackNormal(vec2 enc){vec2 fenc=enc*4.0-2.0;float f=dot(fenc,fenc);float g=sqrt(1.0-f/4.0);return vec3(fenc*g,1.0-f/2.0);}float unpackDepth(vec2 uncodedDepth){float x=unpack16(uncodedDepth.xy);return x*x;}
#define getDepth(uv) unpackDepth(texture2D(tNormalDepth, uv).xy)
void getDepthNormal(const in vec2 uv,out float depth,out vec3 normal){vec4 uncodedDepth=texture2D(tNormalDepth,uv);depth=unpackDepth(uncodedDepth.xy);normal=unpackNormal(uncodedDepth.zw);}vec3 getViewNormal(const in vec2 uv){return unpackNormal(texture2D(tNormalDepth,uv).zw);}
#if defined(GBUFFER_HAS_FLAGS) && GBUFFER_HAS_FLAGS == 1
uniform sampler2D tGBufferFlags;
#endif
ivec4 getGBufferFlags(const in vec2 uv){
#if defined(GBUFFER_HAS_FLAGS) && GBUFFER_HAS_FLAGS == 1
return ivec4(texture2D(tGBufferFlags,uv)*255.);
#else
return ivec4(1);
#endif
}
#if defined(GBUFFER_HAS_DEPTH_TEXTURE) && GBUFFER_HAS_DEPTH_TEXTURE == 1
uniform sampler2D tGBufferDepthTexture;float getDepthTexture(vec2 coord,float cameraNear,float cameraFar){float fragCoordZ=texture2D(tGBufferDepthTexture,coord).x;float viewZ=perspectiveDepthToViewZ(fragCoordZ,cameraNear,cameraFar);return viewZToOrthographicDepth(viewZ,cameraNear,cameraFar);}
#endif
#endif
`;var AV=Object.defineProperty,yV=Object.getOwnPropertyDescriptor,vg=(r,e,t,i)=>{for(var n=i>1?void 0:i?yV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&AV(e,t,n),n};f.GBufferPlugin=class extends Tl{constructor(e=Wt,t=!0,i=!0,n=!0,s=!1,a=ea){super(),this.renderFlagsBuffer=n,this.renderDepthTexture=s,this.depthTextureType=a,this.passId="gbuffer",this.textures=[],this.unpackExtension={shaderExtender:o=>{const c=["gbuffer_unpack","packing"].find(h=>o.fragmentShader.includes(`#include <${h}>`));o.fragmentShader=At(o.fragmentShader,`#include <${c}>`,`
`+D1+`
`,{append:c==="packing"})},extraUniforms:{tNormalDepth:()=>({value:this.normalDepthTexture}),tGBufferFlags:()=>({value:this.flagsTexture}),tGBufferDepthTexture:()=>({value:this.depthTexture})},extraDefines:{HAS_NORMAL_DEPTH_BUFFER:()=>this.normalDepthTexture?1:void 0,GBUFFER_HAS_DEPTH_TEXTURE:()=>this.depthTexture?1:void 0,GBUFFER_HAS_FLAGS:()=>this.flagsTexture?1:void 0,HAS_GBUFFER:()=>this.isPrimaryGBuffer&&this.normalDepthTexture?1:void 0},priority:100,isCompatible:()=>!0},this._isPrimaryGBufferSet=!1,this.enabled=i,this.bufferType=e,this.isPrimaryGBuffer=t}get normalDepthTexture(){return this.textures[0]}get flagsTexture(){return this.textures[1]}get depthTexture(){return this.target?.depthTexture}createMaterial(){const e=this._viewer?.renderManager.isWebGL2&&this.renderFlagsBuffer;return new km(e,{blending:gn,transparent:!0})}_createTargetAndMaterial(e=!0){if(!this._viewer)return;e&&this._disposeTarget();const t=this._viewer?.renderManager.isWebGL2&&this.renderFlagsBuffer;if(!this.target){const i=this._viewer.renderManager;this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:this._viewer.renderManager.zPrepass&&this.isPrimaryGBuffer&&i.msaa?typeof i.msaa!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:i.msaa:0,type:this.bufferType,textureCount:t?2:1,depthTexture:this.renderDepthTexture,depthTextureType:this.depthTextureType,wrapS:ui,wrapT:ui}),Array.isArray(this.target.textures)&&this.target.textures.length>1?(this.target.textures[0].name="gbufferDepthNormal",this.target.textures[1].name="gbufferFlags",this.textures=[...this.target.textures]):(this.target.texture.name="gbufferDepthNormal",this.textures.push(this.target.texture))}this.material||(this.material=this.createMaterial()),this.isPrimaryGBuffer&&(this._viewer.renderManager.gbufferTarget=this.target,this._viewer.renderManager.gbufferUnpackExtension=this.unpackExtension,this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension]),this._isPrimaryGBufferSet=!0)}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.textures=[],this._isPrimaryGBufferSet&&(this._viewer.renderManager.gbufferTarget=void 0,this._viewer.renderManager.gbufferUnpackExtension=void 0,this._isPrimaryGBufferSet=!1))}_createPass(){if(this._createTargetAndMaterial(!0),!this.target)throw new Error("GBufferPlugin: target not created");if(!this.material)throw new Error("GBufferPlugin: material not created");this.material.userData.isGBufferMaterial=!0;const e=new f.GBufferRenderPass(this.passId,()=>this.target,this.material,new se(1,1,1),1),t=e.preprocessMaterial;return e.preprocessMaterial=i=>t(i,i.userData.renderToDepth),e.preprocessObject=i=>{if(i.customGBufferMaterial){const n=i.customGBufferMaterial;n.allowOverride=!1;const s=i.material;i.forcedOverrideMaterial=n;const a=Array.isArray(s)?s[0]:s;return a&&(n.userData.renderToGBuffer=a.userData.renderToGBuffer,n.userData.renderToDepth=a.userData.renderToDepth,n.userData.pluginsDisabled=a.userData.pluginsDisabled,n.side=a.side),n}return i.material},e.postprocessObject=i=>{i.customGBufferMaterial&&delete i.forcedOverrideMaterial},e.before=["render"],e.after=[],e.required=["render"],e}_beforeRender(e,t,i){return!(!super._beforeRender(e,t,i)||!this.material)}registerGBufferUpdater(e,t){this.material&&this.material.flagUpdaters.set(e,t)}unregisterGBufferUpdater(e){this.material&&this.material.flagUpdaters.delete(e)}onRemove(e){return this._disposeTarget(),this.material?.dispose(),this.material=void 0,super.onRemove(e)}getDepthNormal(){return this.textures.length>0?this.textures[0]:void 0}getFlagsTexture(){return this.textures.length>1?this.textures[1]:void 0}getTarget(){return this.target}getUnpackSnippet(){return D1}updateShaderProperties(e){if(e.uniforms.tNormalDepth?e.uniforms.tNormalDepth.value=this.normalDepthTexture??void 0:this._viewer?.console.warn("BaseRenderer: no uniform: tNormalDepth"),e.uniforms.tGBufferFlags){e.uniforms.tGBufferFlags.value=this.flagsTexture??void 0;const t=e.uniforms.tGBufferFlags.value?1:0;t!==e.defines.GBUFFER_HAS_FLAGS&&(e.defines.GBUFFER_HAS_FLAGS=t,e.needsUpdate=!0)}return this}},f.GBufferPlugin.PluginType="GBuffer",vg([Dr(void 0,{readOnly:!0})],f.GBufferPlugin.prototype,"normalDepthTexture",1),vg([Dr(void 0,{readOnly:!0})],f.GBufferPlugin.prototype,"flagsTexture",1),vg([Dr(void 0,{readOnly:!0})],f.GBufferPlugin.prototype,"depthTexture",1),f.GBufferPlugin=vg([gt("G-Buffer Plugin")],f.GBufferPlugin);class Gd extends pt{constructor(e=""){super(),this.priority=-100,this._shaderPatch="",this.computeCacheKey=t=>this.isDisabled()?"0":"1",this._shaderPatch=e,this.setDirty=this.setDirty.bind(this)}set uniformsNeedUpdate(e){e&&this.setDirty()}shaderExtender(e,t,i){this.isDisabled()||(e.fragmentShader=At(e.fragmentShader,"#glMarker",`
`+this._shaderPatch+`
`,{prepend:!0}))}getUiConfig(){return this.uiConfig}isCompatible(e){return!0}setDirty(){this.__setDirty?.(),this._viewer?.renderManager.screenPass.setDirty()}fromJSON(e,t){return e.pass&&(e={...e},e.extension={...e.pass},delete e.extension.enabled,delete e.pass),e.extension&&(e={...e,...e.extension},delete e.extension),super.fromJSON(e,t)}onAdded(e){super.onAdded(e),e.forPlugin(f.GBufferPlugin,t=>{t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this))},t=>{t.unregisterGBufferUpdater(this.constructor.PluginType)},this),e.renderManager.screenPass.material.registerMaterialExtensions([this])}onRemove(e){e.getPlugin(f.GBufferPlugin)?.unregisterGBufferUpdater(this.constructor.PluginType),e.renderManager.screenPass.material.unregisterMaterialExtensions([this]),super.onRemove(e)}updateGBufferFlags(e,t){}}var vV=Object.defineProperty,_V=Object.getOwnPropertyDescriptor,Il=(r,e,t,i)=>{for(var n=i>1?void 0:i?_V(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&vV(e,t,n),n};const bV=Ob;f.TonemapPlugin=class extends Gd{constructor(){super(...arguments),this.extraUniforms={toneMappingContrast:{value:1},toneMappingSaturation:{value:1}},this.extraDefines={TONEMAP_BACKGROUND:()=>this.tonemapBackground===!1||this._viewer?.scene.backgroundTonemap===!1?"0":"1"},this.enabled=!0,this.toneMapping=aA,this.tonemapBackground=!0,this.exposure=1,this.priority=-100,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float toneMappingContrast;
            uniform float toneMappingSaturation;
            ${pV}
        `,this._shaderPatch=mV,this._rendererState={}}onObjectRender(e,t,i){if(this.isDisabled())return;const{toneMapping:n,toneMappingExposure:s}=i;this._rendererState.toneMapping=n,this._rendererState.toneMappingExposure=s,i.toneMapping=this.toneMapping,i.toneMappingExposure=this.exposure,t.toneMapped=!0,t.needsUpdate=!0}onAfterRender(e,t,i){i.toneMapping=this._rendererState.toneMapping,i.toneMappingExposure=this._rendererState.toneMappingExposure}fromJSON(e,t){return e.extension&&e.clipBackground!==void 0&&(this._viewer?this._viewer.renderManager.screenPass.clipBackground=e.clipBackground:console.warn("TonemapPlugin: no viewer attached, clipBackground ignored"),delete e.clipBackground),super.fromJSON(e,t)}updateGBufferFlags(e,t){const i=(t.material.userData.gBufferData?.tonemapEnabled??t.material?.userData.postTonemap)===!1?0:1;e.w=Jy(e.w,1,i),super.updateGBufferFlags(e,t)}},f.TonemapPlugin.PluginType="Tonemap",ot.tonemapping_pars_fragment=ot.tonemapping_pars_fragment.replace("vec3 CustomToneMapping( vec3 color ) { return color; }",fV),Il([z(),de(f.TonemapPlugin.prototype.setDirty),ae("Enabled")],f.TonemapPlugin.prototype,"enabled",2),Il([Oi("Mode",[["Linear",Rb],["Reinhard",Bb],["Cineon",Lb],["ACESFilmic",aA],["Uncharted2",bV],["AgX",Ub]].map(r=>({label:r[0],value:r[1]}))),de(f.TonemapPlugin.prototype.setDirty),z()],f.TonemapPlugin.prototype,"toneMapping",2),Il([de(f.TonemapPlugin.prototype.setDirty),z()],f.TonemapPlugin.prototype,"tonemapBackground",2),Il([de(f.TonemapPlugin.prototype.setDirty),Oe("Exposure",[0,2*Math.PI],.01),z()],f.TonemapPlugin.prototype,"exposure",2),Il([Oe("Saturation",[0,2],.01),va({propKey:"toneMappingSaturation"}),z()],f.TonemapPlugin.prototype,"saturation",2),Il([Oe("Contrast",[0,2],.01),va({propKey:"toneMappingContrast"}),z()],f.TonemapPlugin.prototype,"contrast",2),f.TonemapPlugin=Il([gt("Tonemapping")],f.TonemapPlugin);const wV="0.5.1";var CV=Object.defineProperty,xV=Object.getOwnPropertyDescriptor,wh=(r,e,t,i)=>{for(var n=i>1?void 0:i?xV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&CV(e,t,n),n};function s_(r){const e=[];let t=Object.getPrototypeOf(r);for(;t;)t.constructor?.PluginType&&e.push(t.constructor.PluginType),t.constructor?.OldPluginType&&e.push(t.constructor.OldPluginType),t=Object.getPrototypeOf(t);return e}f.ThreeViewer=class extends wi{constructor({debug:e=!1,...t}){super(),this.type="ThreeViewer",this.enabled=!0,this.renderEnabled=!0,this.timeline=new f.ViewerTimeline,this.plugins={},this.maxFramePerLoop=1,this.rendersPerFrame=1,this.resizeObserver=window?.ResizeObserver?new window.ResizeObserver(o=>this.resize()):void 0,this._needsResize=!1,this._isRenderingFrame=!1,this._needsReset=!0,this._lastCameraPosition=new x,this._lastCameraQuat=new Qe,this._lastCameraTarget=new x,this._tempVec=new x,this._tempQuat=new Qe,this._lastMainCamera=void 0,this.serializePluginsIgnored=[],this.resize=()=>{this._needsResize=!0,this.setDirty()},this.deleteImportedViewerConfigOnLoad=!0,this.deleteImportedViewerConfigOnLoadWait=2e3,this.loadConfigResources=async(o,l)=>{if(o.__isLoadedResources)return o;const c=Gv(o,this);return await Em.ImportMeta(c,l)},this._setActiveCameraView=o=>{if(o.type==="setView"){if(!o.camera){this.console.warn("Cannot find camera",o);return}this._scene.mainCamera.setViewFromCamera(o.camera)}else if(o.type==="activateMain"){let l=o.camera;l===void 0&&this._lastMainCamera&&(this._lastMainCamera.parent&&(l=this._lastMainCamera),this._lastMainCamera=void 0),l&&this._scene.mainCamera!==l&&(this._lastMainCamera=this._scene.mainCamera),l?.setCanvas(this._canvas,!1),this._scene.mainCamera=l===null?void 0:l||void 0}},this._defaultConfig={assetType:"config",type:this.type,version:f.ThreeViewer.VERSION,metadata:{generator:"ThreePipe",version:2},plugins:[]},this._lastSize=new $,this._onContextRestore=o=>{this.enabled=!0,this._canvas.width=this._lastSize.width,this._canvas.height=this._lastSize.height,this.resize(),this._scene.setDirty({refreshScene:!0,frameFade:!1})},this._onContextLost=o=>{this._lastSize.set(this._canvas.width,this._canvas.height),this._canvas.width=2,this._canvas.height=2,this.resize(),this.enabled=!1},this._stopPropagation=o=>{this.scene.mainCamera.canUserInteract&&o.stopPropagation()},this._onListeners={},this._pluginListeners={add:[],remove:[]},this.debug=e,e&&(f.ThreeViewer.ViewerDebugging=!0),this._canvas=t.canvas||Nx();const i=getComputedStyle(this._canvas);!this._canvas.style.width&&i.maxWidth==="none"&&(this._canvas.style.width="100%"),!this._canvas.style.height&&i.maxHeight==="none"&&(this._canvas.style.height="100%");let n=t.container;if(n&&!t.canvas&&n.appendChild(this._canvas),n||(n=this._canvas.parentElement??void 0),n||(n=globalThis.document?.body),!n)throw new Error("No container(or canvas).");this._container=n,this.setDirty=this.setDirty.bind(this),this._animationLoop=this._animationLoop.bind(this),e&&t.statsJS!==!1&&(this.renderStats=new gS(this._container),this.renderStats.show()),window.threeViewers||(window.threeViewers=[]),window.threeViewers.push(this);let s;if(t.camera?.isCamera)s=t.camera,s.assetType||ct.upgradeCamera.call(s);else{s=t.camera?.type==="orthographic"?new yd(t.camera?.controlsMode??"orbit",this._canvas):new th(t.camera?.controlsMode??"orbit",this._canvas),s.name="Default Camera"+(s.type==="OrthographicCamera"?" (Ortho)":"");const o=t.camera?.position||[0,0,5];Array.isArray(o)?s.position.fromArray(o):s.position.copy(o);const l=t.camera?.target||[0,0,0];Array.isArray(l)?s.target.fromArray(l):s.target.copy(l),s.setDirty(),s.userData.autoLookAtTarget=!0,t.rootScene&&this.console.error("ThreeViewer: Camera must also be passed in options when rootScene is passed in options.")}this.addEventListener("postFrame",()=>{const o=this._scene.mainCamera;if(o&&o.canUserInteract){const l=this.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();if(l!==void 0&&l===0)return;typeof o.controls?.update=="function"&&o.controls?.update()}}),this.addEventListener("preFrame",()=>{const o=this._scene.mainCamera;o.getWorldPosition(this._tempVec).sub(this._lastCameraPosition).lengthSq()+this._tempVec.subVectors(o.target,this._lastCameraTarget).lengthSq()+o.getWorldQuaternion(this._tempQuat).angleTo(this._lastCameraQuat)>1e-6&&o.setDirty()}),this.object3dManager=new Ag,this._scene=t.rootScene??new f.RootScene(s,hM(this)),this._scene.mainCamera!==s&&(this._scene.mainCamera=s),this._scene.setBackgroundColor(t.backgroundColor??"#ffffff"),this._scene.addEventListener("setView",this._setActiveCameraView),this._scene.addEventListener("activateMain",this._setActiveCameraView),this._scene.addEventListener("materialUpdate",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("materialChanged",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("objectUpdate",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("textureUpdate",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("sceneUpdate",o=>{this.setDirty(this._scene,o),o.geometryChanged!==!1&&this.renderManager.resetShadows()}),this._scene.addEventListener("mainCameraUpdate",()=>{this._scene.mainCamera.getWorldPosition(this._lastCameraPosition),this._lastCameraTarget.copy(this._scene.mainCamera.target),this._scene.mainCamera.getWorldQuaternion(this._lastCameraQuat)}),this._scene.modelRoot.scale.setScalar(t.modelRootScale??1),this.object3dManager.setRoot(this._scene),(t.isAntialiased!==void 0||t.useRgbm!==void 0||t.useGBufferDepth!==void 0)&&this.console.warn("isAntialiased, useRgbm and useGBufferDepth are deprecated, use msaa, rgbm and zPrepass instead.");const a=t.rmClass??f.ViewerRenderManager;this.renderManager=new a({canvas:this._canvas,msaa:t.msaa??t.isAntialiased??!1,rgbm:t.rgbm??t.useRgbm??!0,zPrepass:t.zPrepass??t.useGBufferDepth??!1,depthBuffer:!(t.zPrepass??t.useGBufferDepth??!1),stencilBuffer:t.stencil,screenShader:t.screenShader,renderScale:typeof t.renderScale=="string"?t.renderScale==="auto"?Math.min(t.maxRenderScale||2,window.devicePixelRatio):parseFloat(t.renderScale):t.renderScale,maxHDRIntensity:t.maxHDRIntensity,powerPreference:t.powerPreference}),this.renderManager.addEventListener("animationLoop",this._animationLoop),this.renderManager.addEventListener("resize",()=>this._scene.mainCamera.refreshAspect()),this.renderManager.addEventListener("update",o=>{o.change==="registerPass"&&o.pass?.materialExtension?this.assetManager.materials.registerMaterialExtension(o.pass.materialExtension):o.change==="unregisterPass"&&o.pass?.materialExtension&&this.assetManager.materials.unregisterMaterialExtension(o.pass.materialExtension),this.setDirty(this.renderManager,o)}),this.assetManager=new gg(this,t.assetManager),t.cacheImportedAssets!==void 0&&(this.assetManager.importer.cacheImportedAssets=t.cacheImportedAssets),this.resizeObserver&&this.resizeObserver.observe(this._canvas),window&&window.addEventListener("resize",this.resize),this._canvas.addEventListener("webglcontextrestored",this._onContextRestore,!1),this._canvas.addEventListener("webglcontextlost",this._onContextLost,!1),t.dropzone&&this.addPluginSync(new f.DropzonePlugin(typeof t.dropzone=="object"?t.dropzone:void 0)),t.tonemap!==!1&&this.addPluginSync(new f.TonemapPlugin);for(const o of t.plugins??[])this.addPluginSync(o);if(this.console.log("ThreePipe Viewer instance initialized, version: ",f.ThreeViewer.VERSION),t.load){const l=[t.load.src].flat().filter(c=>c).map(async c=>c&&this.load(c));t.load.environment&&l.push(this.setEnvironmentMap(t.load.environment)),t.load.background&&l.push(this.setBackgroundMap(t.load.background)),Promise.all(l).then(t.onLoad)}t.stopPointerEventPropagation&&(this._canvas.addEventListener("pointerdown",this._stopPropagation),this._canvas.addEventListener("touchstart",this._stopPropagation),this._canvas.addEventListener("mousedown",this._stopPropagation))}get materialManager(){return this.assetManager.materials}get scene(){return this._scene}get container(){return this._canvas.parentElement!==this._container&&this.console.error("ThreeViewer: Canvas is not in the container, this might cause issues with some plugins."),this._container}get canvas(){return this._canvas}get console(){return f.ThreeViewer.Console}get dialog(){return f.ThreeViewer.Dialog}async load(e,t){if(e)return await this.assetManager.addAssetSingle(e,t)}async import(e,t){if(e)return await this.assetManager.importer.importSingle(e,t)}async setEnvironmentMap(e,{setBackground:t=!1,...i}={}){return this._scene.environment=e&&!e.isTexture?await this.assetManager.importer.importSingle(e,i)||null:e||null,t?this.setBackgroundMap(this._scene.environment):this._scene.environment}async setBackgroundMap(e,{setEnvironment:t=!1,...i}={}){return this._scene.background=e&&!e.isTexture?await this.assetManager.importer.importSingle(e,i)||null:e||null,t?this.setEnvironmentMap(this._scene.background):this._scene.background}async export(e,t){return e||(e=this._scene.modelRoot),e.type===this.type?zv(e.exportConfig()):e.constructor?.PluginType?zv(this.exportPluginConfig(e)):await this.assetManager.exporter.exportObject(e,t)}async exportScene(e,t=!0){const i=t?this.getPlugin("AssetExporterPlugin"):void 0;return i?i.exportScene(e):this.assetManager.exporter.exportObject(this._scene.modelRoot,e)}async getScreenshotBlob({mimeType:e="image/jpeg",quality:t=90}={}){const i=this.getPlugin("CanvasSnapshotPlugin");if(i)return i.getFile("snapshot."+e.split("/")[1],{mimeType:e,quality:t,waitForProgressive:!0});const n=async()=>new Promise(s=>{this._canvas.toBlob(a=>{s(a)},e,t)});return this.renderEnabled?await this.doOnce("postFrame",async()=>{this.renderEnabled=!1;const s=await n();return this.renderEnabled=!0,s}):n()}async getScreenshotDataUrl({mimeType:e="image/jpeg",quality:t=.9}={}){return this.renderEnabled?await this.doOnce("postFrame",()=>this._canvas.toDataURL(e,t)):this._canvas.toDataURL(e,t)}dispose(e=!0){if(this.renderEnabled=!1,e){const t=[],i=[];for(const[n,s]of[...Object.entries(this.plugins)])n!==s.constructor.OldPluginType&&(s.isViewerPluginSync?t.push(s):i.push(s));for(const n of t)this.removePluginSync(n,!0);for(const n of i)this.removePlugin(n,!0)}this._scene.dispose(e),this.renderManager.dispose(e),e&&(this.object3dManager.dispose(),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestore,!1),this._canvas.removeEventListener("webglcontextlost",this._onContextLost,!1),window.threeViewers?.splice(window.threeViewers.indexOf(this),1),this.resizeObserver&&this.resizeObserver.unobserve(this._canvas),window.removeEventListener("resize",this.resize)),this.dispatchEvent({type:"dispose",clear:e})}setDirty(e,t){this._needsReset=!0,e=e??this,this.dispatchEvent({...t??{},type:"update",source:e})}_animationLoop(e){if(this.enabled){if(this._isRenderingFrame){this.console.warn("animation loop: frame skip");return}this._isRenderingFrame=!0,this.renderStats?.begin();for(let t=0;t<this.maxFramePerLoop;t++){let i=!1;if(this.renderEnabled&&(this._needsReset&&(this.renderManager.reset(),this._needsReset=!1),this._needsResize)){const n=[Math.floor(this._canvas.clientWidth),Math.floor(this._canvas.clientHeight)];if(e.xrFrame){const s=this.renderManager.webglRenderer.xr.getCamera()?.cameras[0]?.viewport;s?((s.x!==0||s.y!==0)&&this.console.warn("x and y must be 0?"),n[0]=s.width,n[1]=s.height,this.console.log("resize for xr",n)):this._needsResize=!1}this._needsResize&&(this.renderManager.setSize(...n),this._needsResize=!1,i=!0)}if(this.dispatchEvent({...e,type:"preFrame",target:this}),this.dispatch("preFrame",{time:e.time,deltaTime:e.deltaTime,timeline:this.timeline,resized:i}),this.renderEnabled){const n=Object.entries(this.plugins).filter(([a,o])=>o.dirty&&a!==o.constructor.OldPluginType);if(n.length>0&&this.setDirty(n),this._needsReset&&(this.renderManager.reset(),this._needsReset=!1),this.renderManager.needsRender)for(let a=0;a<this.rendersPerFrame;a++){this._scene._isMainRendering=!0,this.dispatchEvent({type:"preRender",target:this});const o=()=>{const l=this._scene.mainCamera;this._scene.renderCamera=l,l.visible&&this.renderManager.render(this._scene,this.renderManager.defaultRenderToScreen)};if(this.debug)o();else try{o()}catch(l){if(this.console.error("ThreeViewer: Uncaught error while rendering frame."),this.console.error(l),this.debug)throw l;this.renderEnabled=!1,this.dispatchEvent({type:"renderError",error:l})}this._scene._isMainRendering=!1,this.dispatchEvent({type:"postRender",target:this})}}this.timeline.update(this),this.dispatchEvent({type:"postFrame",target:this}),this.renderEnabled&&this.renderManager.onPostFrame(),this.object3dManager.onPostFrame(this.timeline),this.timeline.update2(this)}this.renderStats?.end(),this._isRenderingFrame=!1}}getPlugin(e){return this.plugins[typeof e=="string"?e:e.PluginType]}getPlugins(e){const t=typeof e=="string"?e:e.PluginType,i=Object.values(this.plugins),n=[];for(const s of i)s_(s).includes(t)&&n.push(s);return n}async getOrAddPlugin(e,...t){const i=this.getPlugin(e);return i||this.addPlugin(e,...t)}getOrAddPluginSync(e,...t){const i=this.getPlugin(e);return i||this.addPluginSync(e,...t)}async addPlugin(e,...t){const i=this._resolvePluginOrClass(e,...t);if(!i)throw new Error("ThreeViewer: Plugin is not defined");const n=i.constructor.PluginType;if(!i.constructor.PluginType)return this.console.error("ThreeViewer: PluginType is not defined for",i),i;for(const a of i.dependencies||[])await this.getOrAddPlugin(a);if(this.plugins[n]){if(this.plugins[n]===i)return i;this.console.error(`ThreeViewer: Plugin of type ${n} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`,this.plugins[n],i),await this.removePlugin(this.plugins[n])}this.plugins[n]=i;const s=i.constructor.OldPluginType;return s&&this.plugins[s]&&this.console.error(`ThreeViewer: Plugin type mismatch ${s}`),s&&(this.plugins[s]=i),await i.onAdded(this),this._onPluginAdd(i),i}addPluginSync(e,...t){const i=this._resolvePluginOrClass(e,...t);if(!i)throw new Error("ThreeViewer: Plugin is not defined");const n=i.constructor.PluginType;if(!i.constructor.PluginType)return this.console.error("ThreeViewer: PluginType is not defined for",i),i;for(const a of i.dependencies||[])this.getOrAddPluginSync(a);if(this.plugins[n]){if(this.plugins[n]===i)return i;this.console.error(`ThreeViewer: Plugin of type ${n} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`,this.plugins[n],i),this.removePluginSync(this.plugins[n])}const s=()=>{this.plugins[n]=i;const a=i.constructor.OldPluginType;a&&this.plugins[a]&&this.console.error(`ThreeViewer: Plugin type mismatch ${a}`),a&&(this.plugins[a]=i),i.onAdded(this)};if(this.debug)s();else try{s()}catch(a){this.console.error("ThreeViewer: Error adding plugin, check console for details",a),delete this.plugins[n]}return this._onPluginAdd(i),i}async addPlugins(e){for(const t of e)await this.addPlugin(t)}addPluginsSync(e){for(const t of e)this.addPluginSync(t)}async removePlugin(e,t=!0){const i=e.constructor.PluginType;this.plugins[i]&&(await e.onRemove(this),this._onPluginRemove(e,t))}removePluginSync(e,t=!0){const i=e.constructor.PluginType;this.plugins[i]&&(e.onRemove(this),this._onPluginRemove(e,t))}setSize(e){this._canvas.style.width=e?.width?e.width+"px":"100%",this._canvas.style.height=e?.height?e.height+"px":"100%",this._canvas.offsetHeight,this.resize()}setRenderSize(e,t="contain",i=1,n){const s=n||this.container.getBoundingClientRect(),a=s.height,o=s.width,l=Math.floor(e.width),c=Math.floor(e.height),h=l/c,u=o/a,d=i;let p,m;switch(t){case"contain":u>h?(p=a*h,m=a):(p=o,m=o/h);break;case"cover":u>h?(p=o,m=o/h):(p=a*h,m=a);break;case"fill":p=o,m=a;break;case"scale-down":l<o&&c<a?(p=l,m=c):u>h?(p=a*h,m=a):(p=o,m=o/h);break;case"none":p=l,m=c;break;default:throw new Error(`Invalid mode: ${t}`)}this.setSize({width:p,height:m}),this.renderManager.renderScale=d*c/m}traverseSceneObjects(e){this._scene.modelRoot.traverse(e)}async addSceneObject(e,t){let i=e;if(e.userData?.rootSceneModelRoot){const n=e;this._scene.loadModelRoot(n,t),t?.importConfig!==!1&&(n.importedViewerConfig?(await this.importConfig(n.importedViewerConfig,n.importedBundledResources),n._deletedImportedViewerConfig&&delete n._deletedImportedViewerConfig):n._deletedImportedViewerConfig&&this.console.error("ThreeViewer - Imported viewer config was deleted, cannot import it again. Set `viewer.deleteImportedViewerConfigOnLoad` to `false` to keep it in the object for reuse workflows.")),this.deleteImportedViewerConfigOnLoad&&n.importedViewerConfig&&setTimeout(()=>{n.importedViewerConfig&&(delete n.importedViewerConfig,n._deletedImportedViewerConfig=!0)},this.deleteImportedViewerConfigOnLoadWait),setTimeout(()=>{n.importedBundledResources&&(delete n.importedBundledResources,n._deletedImportedBundledResources=!0)},this.deleteImportedViewerConfigOnLoadWait),i=this._scene.modelRoot}else this._scene.addObject(e,t);return i}serializePlugins(e,t){return t&&t.length===0?[]:t?.map(i=>{const n=this.getPlugin(i);return n?this.serializePlugin(n,e):void 0}).filter(i=>!!i)??Object.entries(this.plugins).map(i=>{if(!(t&&!t.includes(i[1].constructor.PluginType))&&i[0]!==i[1].constructor.OldPluginType)return this.serializePlugin(i[1],e)}).filter(i=>!!i)}serializePlugin(e,t){if(!this.serializePluginsIgnored.includes(e.constructor.PluginType))return e.serializeWithViewer!==!1?e.toJSON?.(t):void 0}deserializePlugins(e,t){return e.forEach(i=>{if(!i.type){this.console.warn("Invalid plugin to import ",i);return}if(this.serializePluginsIgnored.includes(i.type))return;const n=this.getPlugin(i.type);n&&n.fromJSON&&n.fromJSON(i,t)}),this}exportPluginConfig(e){if((e&&typeof e=="string"||e.PluginType)&&(e=this.getPlugin(e)),!e)return{};const t=Fr(),i=e.toJSON?.(t);return i?(i.resources=od(t),i):{}}async importPluginConfig(e,t){const i=e.type;if(t=t||this.getPlugin(i),!t){this.console.warn(`No plugin found for type ${i} to import config`);return}if(!t.fromJSON){this.console.warn(`Plugin ${i} does not support importing presets`);return}const n=e.resources||{};e.resources&&delete e.resources;const s=await this.loadConfigResources(n);return await t.fromJSON(e,s),s&&(e.resources=s),t}exportPluginsConfig(e){const t=Fr(),i=this.serializePlugins(t,e);return kv(t),{...this._defaultConfig,plugins:i,resources:od(t)}}exportConfig(e=!1,t){return this.toJSON(e,t)}async importConfig(e,t){if(e.type!==this.type&&e.type!=="ViewerApp"&&e.type!=="ThreeViewer"){if(this.getPlugin(e.type))return this.importPluginConfig(e);this.console.error(`Unknown config type ${e.type} to import`);return}let i=await this.loadConfigResources(e.resources||{});if(t){const n={_context:i._context},s=[...Object.keys(i),...Object.keys(t||{})];for(const a of s)a==="object"?n[a]=i[a]||t[a]:n[a]={...i[a],...t[a]};i=n}return e.resources=i,this.fromJSON(e,i),this}toJSON(e=!0,t,i){typeof e!="boolean"&&(e=!0),t!==void 0&&!Array.isArray(t)&&(t=void 0),i=i||Fr();const n=Object.assign({...this._defaultConfig,metadata:{...this._defaultConfig.metadata},plugins:this.serializePlugins(i,t)},ke.Serialize(this,i,!0));return e||kv(i),n.resources=od(i),n}fromJSON(e,t){const i={...e};return t&&i.metadata&&i.type==="ViewerApp"&&(t._configMetadata={...i.metadata,viewerVersion:i.version}),i.backgroundIntensity!==void 0&&i.scene?.backgroundIntensity===void 0&&(this.console.warn("old file format, backgroundIntensity moved to RootScene"),this._scene.backgroundIntensity=i.backgroundIntensity,delete i.backgroundIntensity),i.useLegacyLights!==void 0&&i.renderManager?.useLegacyLights===void 0&&(this.console.warn("old file format, useLegacyLights moved to RenderManager"),this.renderManager.useLegacyLights=i.useLegacyLights,delete i.useLegacyLights),i.background!==void 0&&i.scene?.background===void 0&&(this.console.warn("old file format, background moved to RootScene"),i.background==="envMapBackground"?i.background="environment":typeof i.background=="number"?i.background=new se().setHex(i.background,Dt):typeof i.background=="string"?i.background=new se().setStyle(i.background,Dt):i.background?.isColor&&(i.background=new se(i.background)),i.background?.isColor?(this._scene.backgroundColor=i.background,this._scene.background=null):i.background?(this._scene.backgroundColor=new se("#ffffff"),i.scene||(i.scene={}),i.scene.background=i.background):(this._scene.backgroundColor=null,this._scene.background=null),delete i.background),!t&&i.resources&&i.resources.__isLoadedResources&&(t=i.resources,delete i.resources),t?.__isLoadedResources?(Array.isArray(i.plugins)&&(this.deserializePlugins(i.plugins,t),delete i.plugins),ke.Deserialize(i,this,t,!0),this):(this.console.error("ThreeViewer: meta in fromJSON is not available or is not loaded resources, call viewer.loadConfigResources first, or directly use viewer.importConfig"),null)}async doOnce(e,t){return new Promise(i=>{const n=async(...s)=>{this.removeEventListener(e,n),i(await t?.(...s))};this.addEventListener(e,n)})}dispatchEvent(e){super.dispatchEvent(e),super.dispatchEvent({...e,type:"*",eType:e.type})}async exportBlob(e,t){const i=this.getPlugin("FileTransferPlugin");if(t=t??e.name??"file",!i){ku(e,t);return}await i.exportFile(e,t)}_resolvePluginOrClass(e,...t){let i;if(e.prototype){const n=this.getPlugin(e);if(n)return this.console.error(`Plugin of type ${n.constructor.PluginType} already exists, no new plugin created`,n),n;try{i=new e(...t)}catch(s){this.console.error("ThreeViewer: Error creating plugin",s);return}}else i=e;return i}_renderEnabledChanged(){this.dispatchEvent({type:this.renderEnabled?"renderEnabled":"renderDisabled"})}async fitToView(e,t=1.5,i,n){await this.getOrAddPluginSync(n_)?.animateToFitObject(e,t,i,n,{min:(this.scene.mainCamera.controls?.minDistance??.5)+.5,max:1e3})}get canvasTexture(){if(!this._canvas)throw new Error("Canvas not found");return this._canvasTexture||(this._canvasTexture=new Wo(this._canvas),this._canvasTexture.flipY=!1,this._canvasTexture.needsUpdate=!0),this._canvasTexture}on(e,t){if(this._onListeners[e]||(this._onListeners[e]=[]),!this._onListeners[e].includes(t))return this._onListeners[e].push(t),()=>this.off(e,t)}off(e,t){const i=this._onListeners[e]?.indexOf(t)??-1;i!==-1&&this._onListeners[e]?.splice(i,1)}dispatch(e,t){const i=this._onListeners[e];if(i){const n=i.slice().sort((s,a)=>(s.order??0)-(a.order??0));for(const s of n)s.callback({...t,type:e,target:this})}}_onPluginAdd(e){const t={type:"addPlugin",target:this,plugin:e};this.dispatchEvent(t);const i=s_(e);this._pluginListeners.add.filter(n=>!n.p.length||n.p.find(s=>i.includes(s))).forEach(n=>n.l(t)),this.setDirty(e)}_onPluginRemove(e,t=!1){const i={type:"removePlugin",target:this,plugin:e};this.dispatchEvent(i);const n=s_(e);this._pluginListeners.remove.filter(s=>!s.p.length||s.p.find(a=>n.includes(a))).forEach(s=>s.l(i)),delete this.plugins[e.constructor.PluginType],e.constructor.OldPluginType&&delete this.plugins[e.constructor.OldPluginType],t&&e.dispose(),this.setDirty(e)}addPluginListener(e,t,...i){this._pluginListeners[e].push({p:i.filter(n=>!!n),l:t})}removePluginListener(e,t){this._pluginListeners[e]=this._pluginListeners[e].filter(i=>i.l!==t)}forPlugin(e,t,i,n){const s=()=>{if(i){const o=()=>{const l=this.getPlugin(e);l&&(this.removePluginListener("remove",o),i(l))};this.addPluginListener("remove",o,typeof e=="string"?e:e.PluginType),n?.constructor.PluginType&&this.addPluginListener("remove",o,n.constructor.PluginType)}},a=this.getPlugin(e);if(a)t(a),s();else{const o=()=>{const l=this.getPlugin(e);l&&(this.removePluginListener("add",o),t(l),s())};this.addPluginListener("add",o,typeof e=="string"?e:e.PluginType,typeof e=="string"?void 0:e.OldPluginType)}}get renderer(){return this.console.error("ThreeViewer: renderer is deprecated, use renderManager instead"),this.renderManager}getManager(){return this.assetManager}getPluginByType(e){return this.plugins[e]}},f.ThreeViewer.VERSION=wV,f.ThreeViewer.ConfigTypeSlug="vjson",f.ThreeViewer.Console={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},f.ThreeViewer.Dialog=uS,f.ThreeViewer.ViewerDebugging=!1,wh([z()],f.ThreeViewer.prototype,"type",2),wh([de(f.ThreeViewer.prototype._renderEnabledChanged),ae("Enable Rendering",{tags:["advanced"]})],f.ThreeViewer.prototype,"renderEnabled",2),wh([Li(void 0,{label:"Rendering",expanded:!0}),z("renderManager")],f.ThreeViewer.prototype,"renderManager",2),wh([Li(void 0,{label:"Scene",expanded:!0}),z("scene")],f.ThreeViewer.prototype,"_scene",2),wh([Li(void 0,{label:"Timeline",expanded:!0,tags:["advanced"]}),z("timeline")],f.ThreeViewer.prototype,"timeline",2),f.ThreeViewer=wh([Aa("Viewer")],f.ThreeViewer);const SV="163",EV={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},MV={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},TV=0,IV=1,PV=2,DV=3,RV=0,BV=1,LV=2,OV=3,UV=0,FV=1,NV=2,kV=0,GV=1,zV=2,VV=3,HV=4,QV=5,jV=100,WV=101,qV=102,XV=103,YV=104,$V=200,KV=201,JV=202,ZV=203,eH=204,tH=205,iH=206,nH=207,sH=208,rH=209,aH=210,oH=211,lH=212,cH=213,hH=214,uH=0,dH=1,fH=2,pH=3,mH=4,gH=5,AH=6,yH=7,vH=0,_H=1,bH=2,wH=0,CH=1,xH=2,SH=3,EH=4,MH=5,TH=6,IH=7,PH="attached",DH="detached",RH=300,BH=301,LH=302,OH=303,UH=304,FH=306,NH=1e3,kH=1001,GH=1002,zH=1003,VH=1004,HH=1004,QH=1005,jH=1005,WH=1006,qH=1007,XH=1007,YH=1008,$H=1008,KH=1009,JH=1010,ZH=1011,eQ=1012,tQ=1013,iQ=1014,nQ=1015,sQ=1016,rQ=1017,aQ=1018,oQ=1020,lQ=35902,cQ=1021,hQ=1022,uQ=1023,dQ=1024,fQ=1025,pQ=1026,mQ=1027,gQ=1028,AQ=1029,yQ=1030,vQ=1031,_Q=1033,bQ=33776,wQ=33777,CQ=33778,xQ=33779,SQ=35840,EQ=35841,MQ=35842,TQ=35843,IQ=36196,PQ=37492,DQ=37496,RQ=37808,BQ=37809,LQ=37810,OQ=37811,UQ=37812,FQ=37813,NQ=37814,kQ=37815,GQ=37816,zQ=37817,VQ=37818,HQ=37819,QQ=37820,jQ=37821,WQ=36492,qQ=36494,XQ=36495,YQ=36283,$Q=36284,KQ=36285,JQ=36286,ZQ=2200,e4=2201,t4=2202,i4=2300,n4=2301,s4=2302,r4=2400,a4=2401,o4=2402,l4=2500,c4=2501,h4=0,u4=1,d4=2,f4=3200,p4=3201,m4=0,g4=1,A4="",y4="srgb",v4="srgb-linear",_4="display-p3",b4="display-p3-linear",w4="rgbm-16",C4="linear",x4="srgb",S4="rec709",E4="p3",M4=0,T4=7680,I4=7681,P4=7682,D4=7683,R4=34055,B4=34056,L4=5386,O4=512,U4=513,F4=514,N4=515,k4=516,G4=517,z4=518,V4=519,H4=512,Q4=513,j4=514,W4=515,q4=516,X4=517,Y4=518,$4=519,K4=35044,J4=35048,Z4=35040,e5=35045,t5=35049,i5=35041,n5=35046,s5=35050,r5=35042,a5="100",o5="300 es",l5=2e3,c5=2001,h5=3e3,u5=3001,R1=new x,B1=new x;class L1 extends ye{constructor(e=new Hs,t=new $c({color:Math.random()*16777215})){super(e,t),this.isWireframe=!0,this.type="Wireframe"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,i=e.attributes.instanceEnd,n=new Float32Array(2*t.count);for(let a=0,o=0,l=t.count;a<l;a++,o+=2)R1.fromBufferAttribute(t,a),B1.fromBufferAttribute(i,a),n[o]=o===0?0:n[o-1],n[o+1]=n[o]+R1.distanceTo(B1);const s=new Ou(n,2,1);return e.setAttribute("instanceDistanceStart",new On(s,1,0)),e.setAttribute("instanceDistanceEnd",new On(s,1,1)),this}}function O1(r,e=1024){const i=new $,n=new $,s=[new $,new $,new $],a=[],o=document.createElement("canvas"),l=e,c=e;o.width=l,o.height=c;const h=o.getContext("2d");h.lineWidth=1,h.strokeStyle="rgb( 63, 63, 63 )",h.textAlign="center",h.fillStyle="rgb( 255, 255, 255 )",h.fillRect(0,0,l,c);const u=r.index,d=r.attributes.uv;if(u)for(let m=0,A=u.count;m<A;m+=3)a[0]=u.getX(m),a[1]=u.getX(m+1),a[2]=u.getX(m+2),s[0].fromBufferAttribute(d,a[0]),s[1].fromBufferAttribute(d,a[1]),s[2].fromBufferAttribute(d,a[2]),p(a,s,m/3);else for(let m=0,A=d.count;m<A;m+=3)a[0]=m,a[1]=m+1,a[2]=m+2,s[0].fromBufferAttribute(d,a[0]),s[1].fromBufferAttribute(d,a[1]),s[2].fromBufferAttribute(d,a[2]),p(a,s,m/3);return o;function p(m,A,g){h.beginPath(),i.set(0,0);for(let y=0,_=A.length;y<_;y++){const v=A[y];i.x+=v.x,i.y+=v.y,y===0?h.moveTo(v.x*(l-2)+.5,(1-v.y)*(c-2)+.5):h.lineTo(v.x*(l-2)+.5,(1-v.y)*(c-2)+.5)}h.closePath(),h.stroke(),i.divideScalar(A.length),h.font="18px Arial",h.fillStyle="rgb( 63, 63, 63 )",h.fillText(g,i.x*l,(1-i.y)*c),i.x>.95&&h.fillText(g,i.x%1*l,(1-i.y)*c),h.font="12px Arial",h.fillStyle="rgb( 191, 191, 191 )";for(let y=0,_=A.length;y<_;y++){const v=A[y];n.addVectors(i,v).divideScalar(2);const b=m[y];h.fillText("abc"[y]+b,n.x*l,(1-n.y)*c),n.x>.95&&h.fillText("abc"[y]+b,n.x%1*l,(1-n.y)*c)}}}class d5{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:n,msg:s,transfer:a}=this.queue.shift();this.workersResolve[e]=n,this.workers[e].postMessage(s,a)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(i=>{const n=this._getIdleWorker();n!==-1?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=i,this.workers[n].postMessage(e,t)):this.queue.push({resolve:i,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const f5=0,U1=2,p5=1,F1=2,m5=0,g5=1,A5=10,y5=0,N1=9,k1=15,G1=16,z1=22,V1=37,H1=43,Q1=76,j1=83,W1=97,q1=100,X1=103,Y1=109,$1=165,K1=166;class v5{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class zd{constructor(e,t,i,n){this._dataView=new DataView(e.buffer,e.byteOffset+t,i),this._littleEndian=n,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+4294967296*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_skip(e){return this._offset+=e,this}_scan(e,t=0){const i=this._offset;let n=0;for(;this._dataView.getUint8(this._offset)!==t&&n<e;)n++,this._offset++;return n<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+i,n)}}const hs=[171,75,84,88,32,50,48,187,13,10,26,10];function J1(r){return typeof TextDecoder<"u"?new TextDecoder().decode(r):Buffer.from(r).toString("utf8")}function _5(r){const e=new Uint8Array(r.buffer,r.byteOffset,hs.length);if(e[0]!==hs[0]||e[1]!==hs[1]||e[2]!==hs[2]||e[3]!==hs[3]||e[4]!==hs[4]||e[5]!==hs[5]||e[6]!==hs[6]||e[7]!==hs[7]||e[8]!==hs[8]||e[9]!==hs[9]||e[10]!==hs[10]||e[11]!==hs[11])throw new Error("Missing KTX 2.0 identifier.");const t=new v5,i=17*Uint32Array.BYTES_PER_ELEMENT,n=new zd(r,hs.length,i,!0);t.vkFormat=n._nextUint32(),t.typeSize=n._nextUint32(),t.pixelWidth=n._nextUint32(),t.pixelHeight=n._nextUint32(),t.pixelDepth=n._nextUint32(),t.layerCount=n._nextUint32(),t.faceCount=n._nextUint32();const s=n._nextUint32();t.supercompressionScheme=n._nextUint32();const a=n._nextUint32(),o=n._nextUint32(),l=n._nextUint32(),c=n._nextUint32(),h=n._nextUint64(),u=n._nextUint64(),d=new zd(r,hs.length+i,3*s*8,!0);for(let K=0;K<s;K++)t.levels.push({levelData:new Uint8Array(r.buffer,r.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const p=new zd(r,a,o,!0),m={vendorId:p._skip(4)._nextUint16(),descriptorType:p._nextUint16(),versionNumber:p._nextUint16(),descriptorBlockSize:p._nextUint16(),colorModel:p._nextUint8(),colorPrimaries:p._nextUint8(),transferFunction:p._nextUint8(),flags:p._nextUint8(),texelBlockDimension:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],bytesPlane:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],samples:[]},A=(m.descriptorBlockSize/4-6)/4;for(let K=0;K<A;K++){const q={bitOffset:p._nextUint16(),bitLength:p._nextUint8(),channelType:p._nextUint8(),samplePosition:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};64&q.channelType?(q.sampleLower=p._nextInt32(),q.sampleUpper=p._nextInt32()):(q.sampleLower=p._nextUint32(),q.sampleUpper=p._nextUint32()),m.samples[K]=q}t.dataFormatDescriptor.length=0,t.dataFormatDescriptor.push(m);const g=new zd(r,l,c,!0);for(;g._offset<c;){const K=g._nextUint32(),q=g._scan(K),oe=J1(q),re=g._scan(K-q.byteLength);t.keyValue[oe]=oe.match(/^ktx/i)?J1(re):re,g._offset%4&&g._skip(4-g._offset%4)}if(u<=0)return t;const y=new zd(r,h,u,!0),_=y._nextUint16(),v=y._nextUint16(),b=y._nextUint32(),T=y._nextUint32(),E=y._nextUint32(),M=y._nextUint32(),S=[];for(let K=0;K<s;K++)S.push({imageFlags:y._nextUint32(),rgbSliceByteOffset:y._nextUint32(),rgbSliceByteLength:y._nextUint32(),alphaSliceByteOffset:y._nextUint32(),alphaSliceByteLength:y._nextUint32()});const w=h+y._offset,C=w+b,D=C+T,O=D+E,F=new Uint8Array(r.buffer,r.byteOffset+w,b),G=new Uint8Array(r.buffer,r.byteOffset+C,T),j=new Uint8Array(r.buffer,r.byteOffset+D,E),W=new Uint8Array(r.buffer,r.byteOffset+O,M);return t.globalData={endpointCount:_,selectorCount:v,imageDescs:S,endpointsData:F,selectorsData:G,tablesData:j,extendedData:W},t}let r_,Ma,a_;const o_={env:{emscripten_notify_memory_growth:function(r){a_=new Uint8Array(Ma.exports.memory.buffer)}}};class b5{init(){return r_||(r_=typeof fetch<"u"?fetch("data:application/wasm;base64,"+Z1).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,o_)).then(this._init):WebAssembly.instantiate(Buffer.from(Z1,"base64"),o_).then(this._init),r_)}_init(e){Ma=e.instance,o_.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!Ma)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=e.byteLength,n=Ma.exports.malloc(i);a_.set(e,n),t=t||Number(Ma.exports.ZSTD_findDecompressedSize(n,i));const s=Ma.exports.malloc(t),a=Ma.exports.ZSTD_decompress(s,t,n,i),o=a_.slice(s,s+a);return Ma.exports.free(n),Ma.exports.free(s),o}}const Z1="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ",l_=new WeakMap;let c_=0,h_;class dr extends li{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new d5,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER<"u"&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return this.workerConfig={astcSupported:await e.hasFeatureAsync("texture-compression-astc"),etc1Supported:await e.hasFeatureAsync("texture-compression-etc1"),etc2Supported:await e.hasFeatureAsync("texture-compression-etc2"),dxtSupported:await e.hasFeatureAsync("texture-compression-bc"),bptcSupported:await e.hasFeatureAsync("texture-compression-bptc"),pvrtcSupported:await e.hasFeatureAsync("texture-compression-pvrtc")},this}detectSupport(e){return e.isWebGPURenderer===!0?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-bc"),bptcSupported:e.hasFeature("texture-compression-bptc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:(this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},this.workerConfig.etc1Supported=!1),this}init(){if(!this.transcoderPending){const e=new Zt(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new Zt(this.manager);i.setPath(this.transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const n=i.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,n]).then(([s,a])=>{const o=dr.BasisWorker,l=["/* constants */","let _EngineFormat = "+JSON.stringify(dr.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(dr.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(dr.BasisFormat),"/* basis_transcoder.js */",s,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([l])),this.transcoderBinary=a,this.workerPool.setWorkerCreator(()=>{const c=new Worker(this.workerSourceURL),h=this.transcoderBinary.slice(0);return c.postMessage({type:"init",config:this.workerConfig,transcoderBinary:h},[h]),c})}),c_>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),c_++}return this.transcoderPending}load(e,t,i,n){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const s=new Zt(this.manager);s.setResponseType("arraybuffer"),s.setCrossOrigin(this.crossOrigin),s.setWithCredentials(this.withCredentials),s.load(e,a=>{if(l_.has(a))return l_.get(a).promise.then(t).catch(n);this.createTexture(a).then(o=>t?t(o):null).catch(n)},i,n)}_createTextureFrom(e,t){const{faces:i,width:n,height:s,format:a,type:o,error:l,dfdFlags:c}=e;if(o==="error")return Promise.reject(l);let h;if(t.faceCount===6)h=new zC(i,a,Wt);else{const u=i[0].mipmaps;h=t.layerCount>1?new GC(u,n,s,t.layerCount,a,Wt):new ua(u,n,s,a,Wt)}return h.minFilter=i[0].mipmaps.length===1?st:Ln,h.magFilter=st,h.generateMipmaps=!1,h.needsUpdate=!0,h.colorSpace=eI(t),h.premultiplyAlpha=!!(c&p5),h}async createTexture(e,t={}){const i=_5(new Uint8Array(e));if(i.vkFormat!==y5)return C5(i);const n=t,s=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:n},[e])).then(a=>this._createTextureFrom(a.data,i));return l_.set(e,{promise:s}),s}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),c_--,this}}dr.BasisFormat={ETC1S:0,UASTC_4x4:1},dr.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},dr.EngineFormat={RGBAFormat:Kt,RGBA_ASTC_4x4_Format:yA,RGBA_BPTC_Format:df,RGBA_ETC2_EAC_Format:AA,RGBA_PVRTC_4BPPV1_Format:pA,RGBA_S3TC_DXT5_Format:hf,RGB_ETC1_Format:mA,RGB_ETC2_Format:gA,RGB_PVRTC_4BPPV1_Format:fA,RGB_S3TC_DXT1_Format:cf},dr.BasisWorker=`function () {

	let config;
	let transcoderPending;
	let BasisModule;

	const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
	const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
	const BasisFormat = _BasisFormat; // eslint-disable-line no-undef

	self.addEventListener( 'message', function ( e ) {

		const message = e.data;

		switch ( message.type ) {

			case 'init':
				config = message.config;
				init( message.transcoderBinary );
				break;

			case 'transcode':
				transcoderPending.then( () => {

					try {

						const { faces, buffers, width, height, hasAlpha, format, dfdFlags } = transcode( message.buffer );

						self.postMessage( { type: 'transcode', id: message.id, faces, width, height, hasAlpha, format, dfdFlags }, buffers );

					} catch ( error ) {

						console.error( error );

						self.postMessage( { type: 'error', id: message.id, error: error.message } );

					}

				} );
				break;

		}

	} );

	function init( wasmBinary ) {

		transcoderPending = new Promise( ( resolve ) => {

			BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
			BASIS( BasisModule ); // eslint-disable-line no-undef

		} ).then( () => {

			BasisModule.initializeBasis();

			if ( BasisModule.KTX2File === undefined ) {

				console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );

			}

		} );

	}

	function transcode( buffer ) {

		const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );

		function cleanup() {

			ktx2File.close();
			ktx2File.delete();

		}

		if ( ! ktx2File.isValid() ) {

			cleanup();
			throw new Error( 'THREE.KTX2Loader:	Invalid or unsupported .ktx2 file' );

		}

		const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
		const width = ktx2File.getWidth();
		const height = ktx2File.getHeight();
		const layerCount = ktx2File.getLayers() || 1;
		const levelCount = ktx2File.getLevels();
		const faceCount = ktx2File.getFaces();
		const hasAlpha = ktx2File.getHasAlpha();
		const dfdFlags = ktx2File.getDFDFlags();

		const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );

		if ( ! width || ! height || ! levelCount ) {

			cleanup();
			throw new Error( 'THREE.KTX2Loader:	Invalid texture' );

		}

		if ( ! ktx2File.startTranscoding() ) {

			cleanup();
			throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );

		}

		const faces = [];
		const buffers = [];

		for ( let face = 0; face < faceCount; face ++ ) {

			const mipmaps = [];

			for ( let mip = 0; mip < levelCount; mip ++ ) {

				const layerMips = [];

				let mipWidth, mipHeight;

				for ( let layer = 0; layer < layerCount; layer ++ ) {

					const levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );

					if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {

						console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );

					}

					if ( levelCount > 1 ) {

						mipWidth = levelInfo.origWidth;
						mipHeight = levelInfo.origHeight;

					} else {

						// Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
						// mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
						// See mrdoob/three.js#25908.
						mipWidth = levelInfo.width;
						mipHeight = levelInfo.height;

					}

					const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
					const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );

					if ( ! status ) {

						cleanup();
						throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );

					}

					layerMips.push( dst );

				}

				const mipData = concat( layerMips );

				mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
				buffers.push( mipData.buffer );

			}

			faces.push( { mipmaps, width, height, format: engineFormat } );

		}

		cleanup();

		return { faces, buffers, width, height, hasAlpha, format: engineFormat, dfdFlags };

	}

	//

	// Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
	// device capabilities, and texture dimensions. The list below ranks the formats separately
	// for ETC1S and UASTC.
	//
	// In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
	// significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
	// chooses RGBA32 only as a last resort and does not expose that option to the caller.
	const FORMAT_OPTIONS = [
		{
			if: 'astcSupported',
			basisFormat: [ BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
			engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
			priorityETC1S: Infinity,
			priorityUASTC: 1,
			needsPowerOfTwo: false,
		},
		{
			if: 'bptcSupported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
			engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
			priorityETC1S: 3,
			priorityUASTC: 2,
			needsPowerOfTwo: false,
		},
		{
			if: 'dxtSupported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
			engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
			priorityETC1S: 4,
			priorityUASTC: 5,
			needsPowerOfTwo: false,
		},
		{
			if: 'etc2Supported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
			engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
			priorityETC1S: 1,
			priorityUASTC: 3,
			needsPowerOfTwo: false,
		},
		{
			if: 'etc1Supported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.ETC1 ],
			engineFormat: [ EngineFormat.RGB_ETC1_Format ],
			priorityETC1S: 2,
			priorityUASTC: 4,
			needsPowerOfTwo: false,
		},
		{
			if: 'pvrtcSupported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
			engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
			priorityETC1S: 5,
			priorityUASTC: 6,
			needsPowerOfTwo: true,
		},
	];

	const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {

		return a.priorityETC1S - b.priorityETC1S;

	} );
	const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {

		return a.priorityUASTC - b.priorityUASTC;

	} );

	function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {

		let transcoderFormat;
		let engineFormat;

		const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;

		for ( let i = 0; i < options.length; i ++ ) {

			const opt = options[ i ];

			if ( ! config[ opt.if ] ) continue;
			if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
			if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
			if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;

			transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
			engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];

			return { transcoderFormat, engineFormat };

		}

		console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );

		transcoderFormat = TranscoderFormat.RGBA32;
		engineFormat = EngineFormat.RGBAFormat;

		return { transcoderFormat, engineFormat };

	}

	function isPowerOfTwo( value ) {

		if ( value <= 2 ) return true;

		return ( value & ( value - 1 ) ) === 0 && value !== 0;

	}

	/** Concatenates N byte arrays. */
	function concat( arrays ) {

		if ( arrays.length === 1 ) return arrays[ 0 ];

		let totalByteLength = 0;

		for ( let i = 0; i < arrays.length; i ++ ) {

			const array = arrays[ i ];
			totalByteLength += array.byteLength;

		}

		const result = new Uint8Array( totalByteLength );

		let byteOffset = 0;

		for ( let i = 0; i < arrays.length; i ++ ) {

			const array = arrays[ i ];
			result.set( array, byteOffset );

			byteOffset += array.byteLength;

		}

		return result;

	}

}`;const w5=new Set([Kt,Kl,ka]),u_={[Y1]:Kt,[W1]:Kt,[V1]:Kt,[H1]:Kt,[X1]:Kl,[j1]:Kl,[G1]:Kl,[z1]:Kl,[q1]:ka,[Q1]:ka,[k1]:ka,[N1]:ka,[K1]:uf,[$1]:uf},d_={[Y1]:zt,[W1]:$t,[V1]:Wt,[H1]:Wt,[X1]:zt,[j1]:$t,[G1]:Wt,[z1]:Wt,[q1]:zt,[Q1]:$t,[k1]:Wt,[N1]:Wt,[K1]:Wt,[$1]:Wt};async function C5(r){const{vkFormat:e}=r;if(u_[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let t;r.supercompressionScheme===U1&&(h_||(h_=new Promise(async s=>{const a=new b5;await a.init(),s(a)})),t=await h_);const i=[];for(let s=0;s<r.levels.length;s++){const a=Math.max(1,r.pixelWidth>>s),o=Math.max(1,r.pixelHeight>>s),l=r.pixelDepth?Math.max(1,r.pixelDepth>>s):0,c=r.levels[s];let h;if(r.supercompressionScheme===f5)h=c.levelData;else if(r.supercompressionScheme===U1)h=t.decode(c.levelData,c.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let u;d_[e]===zt?u=new Float32Array(h.buffer,h.byteOffset,h.byteLength/Float32Array.BYTES_PER_ELEMENT):d_[e]===$t?u=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT):u=h,i.push({data:u,width:a,height:o,depth:l})}let n;if(w5.has(u_[e]))n=r.pixelDepth===0?new As(i[0].data,r.pixelWidth,r.pixelHeight):new wf(i[0].data,r.pixelWidth,r.pixelHeight,r.pixelDepth);else{if(r.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");n=new ua(i,r.pixelWidth,r.pixelHeight)}return n.mipmaps=i,n.type=d_[e],n.format=u_[e],n.colorSpace=eI(r),n.needsUpdate=!0,Promise.resolve(n)}function eI(r){const e=r.dataFormatDescriptor[0];return e.colorPrimaries===g5?e.transferFunction===F1?vt:Dt:e.colorPrimaries===A5?e.transferFunction===F1?eu:tu:(e.colorPrimaries===m5||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),si)}class tI extends lx{constructor(e){super(e)}parse(e,t){const i=new E5(e,1);return{mipmaps:i.mipmaps(t),width:i.pixelWidth,height:i.pixelHeight,format:i.glInternalFormat,isCubemap:i.numberOfFaces===6,mipmapCount:i.numberOfMipmapLevels}}}const x5=64,S5=0;class E5{constructor(e,t){this.arrayBuffer=e;const i=new Uint8Array(this.arrayBuffer,0,12);if(i[0]!==171||i[1]!==75||i[2]!==84||i[3]!==88||i[4]!==32||i[5]!==49||i[6]!==49||i[7]!==187||i[8]!==13||i[9]!==10||i[10]!==26||i[11]!==10){console.error("texture missing KTX identifier");return}const n=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.arrayBuffer,12,13*n),o=s.getUint32(0,!0)===67305985;if(this.glType=s.getUint32(1*n,o),this.glTypeSize=s.getUint32(2*n,o),this.glFormat=s.getUint32(3*n,o),this.glInternalFormat=s.getUint32(4*n,o),this.glBaseInternalFormat=s.getUint32(5*n,o),this.pixelWidth=s.getUint32(6*n,o),this.pixelHeight=s.getUint32(7*n,o),this.pixelDepth=s.getUint32(8*n,o),this.numberOfArrayElements=s.getUint32(9*n,o),this.numberOfFaces=s.getUint32(10*n,o),this.numberOfMipmapLevels=s.getUint32(11*n,o),this.bytesOfKeyValueData=s.getUint32(12*n,o),this.glType!==0){console.warn("only compressed formats currently supported");return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){console.warn("only 2D textures currently supported");return}if(this.numberOfArrayElements!==0){console.warn("texture arrays not currently supported");return}if(this.numberOfFaces!==t){console.warn("number of faces expected"+t+", but found "+this.numberOfFaces);return}this.loadType=S5}mipmaps(e){const t=[];let i=x5+this.bytesOfKeyValueData,n=this.pixelWidth,s=this.pixelHeight;const a=e?this.numberOfMipmapLevels:1;for(let o=0;o<a;o++){const l=new Int32Array(this.arrayBuffer,i,1)[0];i+=4;for(let c=0;c<this.numberOfFaces;c++){const h=new Uint8Array(this.arrayBuffer,i,l);t.push({data:h,width:n,height:s}),i+=l,i+=3-(l+3)%4}n=Math.max(1,n*.5),s=Math.max(1,s*.5)}return t}}class M5{parse(e){const t={},i=e.split(`
`);let n=null,s=t;const a=[t];for(const o of i)if(o.includes("=")){const l=o.split("="),c=l[0].trim(),h=l[1].trim();if(h.endsWith("{")){const u={};a.push(u),s[c]=u,s=u}else s[c]=h}else if(o.endsWith("{")){const l=s[n]||{};a.push(l),s[n]=l,s=l}else if(o.endsWith("}")){if(a.pop(),a.length===0)continue;s=a[a.length-1]}else if(o.endsWith("(")){const l={};a.push(l),n=o.split("(")[0].trim()||n,s[n]=l,s=l}else o.endsWith(")")?(a.pop(),s=a[a.length-1]):n=o.trim();return t}}class iI extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new Zt(s.manager);a.setPath(s.path),a.setResponseType("arraybuffer"),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t=new M5;function i(S){const w={};new Zt().setResponseType("arraybuffer");for(const D in S){if(D.endsWith("png")){const O=new Blob([S[D]],{type:{type:"image/png"}});w[D]=URL.createObjectURL(O)}if(D.endsWith("usd")||D.endsWith("usda")){if(n(S[D])){console.warn("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.");continue}const O=Fd(S[D]);w[D]=t.parse(O)}}return w}function n(S){const w=S.slice(0,7),C=new Uint8Array([80,88,82,45,85,83,68,67]);return w.every((D,O)=>D===C[O])}function s(S){if(S.length<1)return;const w=Object.keys(S)[0];let C=!1;if(w.endsWith("usda"))return S[w];if(w.endsWith("usdc"))C=!0;else if(w.endsWith("usd"))if(n(S[w]))C=!0;else return S[w];C&&console.warn("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.")}const a=Y0(new Uint8Array(e)),o=i(a),l=s(a);if(l===void 0)return console.warn("THREE.USDZLoader: No usda file found."),new Ri;const c=Fd(l),h=t.parse(c);function u(S){if(S){if("prepend references"in S){const C=S["prepend references"].split("@"),D=C[1].replace(/^.\//,""),O=C[2].replace(/^<\//,"").replace(/>$/,"");return d(o[D],O)}return d(S)}}function d(S,w){if(S){if(w!==void 0){const C=`def Mesh "${w}"`;if(C in S)return S[C]}for(const C in S){const D=S[C];if(C.startsWith("def Mesh"))return"point3f[] points"in S&&(D["point3f[] points"]=S["point3f[] points"]),"texCoord2f[] primvars:st"in S&&(D["texCoord2f[] primvars:st"]=S["texCoord2f[] primvars:st"]),"int[] primvars:st:indices"in S&&(D["int[] primvars:st:indices"]=S["int[] primvars:st:indices"]),D;if(typeof D=="object"){const O=d(D);if(O)return O}}}}function p(S){if(!S)return;let w=new $e;if("int[] faceVertexIndices"in S){const C=JSON.parse(S["int[] faceVertexIndices"]);w.setIndex(C)}if("point3f[] points"in S){const C=JSON.parse(S["point3f[] points"].replace(/[()]*/g,"")),D=new Xe(new Float32Array(C),3);w.setAttribute("position",D)}if("normal3f[] normals"in S){const C=JSON.parse(S["normal3f[] normals"].replace(/[()]*/g,"")),D=new Xe(new Float32Array(C),3);w.setAttribute("normal",D)}else w.computeVertexNormals();if("float2[] primvars:st"in S&&(S["texCoord2f[] primvars:st"]=S["float2[] primvars:st"]),"texCoord2f[] primvars:st"in S){const C=JSON.parse(S["texCoord2f[] primvars:st"].replace(/[()]*/g,"")),D=new Xe(new Float32Array(C),2);if("int[] primvars:st:indices"in S){w=w.toNonIndexed();const O=JSON.parse(S["int[] primvars:st:indices"]);w.setAttribute("uv",m(D,O))}else w.setAttribute("uv",D)}return w}function m(S,w){const C=S.array,D=S.itemSize,O=new C.constructor(w.length*D);let F=0,G=0;for(let j=0,W=w.length;j<W;j++){F=w[j]*D;for(let K=0;K<D;K++)O[G++]=C[F++]}return new Xe(O,D)}function A(S){if(S){if("rel material:binding"in S){const D=S["rel material:binding"].replace(/^<\//,"").replace(/>$/,"").split("/");return g(h,` "${D[1]}"`)}return g(S)}}function g(S,w=""){for(const C in S){const D=S[C];if(C.startsWith("def Material"+w))return D;if(typeof D=="object"){const O=g(D,w);if(O)return O}}}function y(S,w){w["float inputs:rotation"]&&(S.rotation=parseFloat(w["float inputs:rotation"])),w["float2 inputs:scale"]&&(S.repeat=new $().fromArray(JSON.parse("["+w["float2 inputs:scale"].replace(/[()]*/g,"")+"]"))),w["float2 inputs:translation"]&&(S.offset=new $().fromArray(JSON.parse("["+w["float2 inputs:translation"].replace(/[()]*/g,"")+"]")))}function _(S){const w=new Nc;if(S!==void 0){if('def Shader "PreviewSurface"'in S){const C=S['def Shader "PreviewSurface"'];if("color3f inputs:diffuseColor.connect"in C){const D=C["color3f inputs:diffuseColor.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.map=b(O),w.map.colorSpace=vt,'def Shader "Transform2d_diffuse"'in S&&y(w.map,S['def Shader "Transform2d_diffuse"'])}else if("color3f inputs:diffuseColor"in C){const D=C["color3f inputs:diffuseColor"].replace(/[()]*/g,"");w.color.fromArray(JSON.parse("["+D+"]"))}if("color3f inputs:emissiveColor.connect"in C){const D=C["color3f inputs:emissiveColor.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.emissiveMap=b(O),w.emissiveMap.colorSpace=vt,w.emissive.set(16777215),'def Shader "Transform2d_emissive"'in S&&y(w.emissiveMap,S['def Shader "Transform2d_emissive"'])}else if("color3f inputs:emissiveColor"in C){const D=C["color3f inputs:emissiveColor"].replace(/[()]*/g,"");w.emissive.fromArray(JSON.parse("["+D+"]"))}if("normal3f inputs:normal.connect"in C){const D=C["normal3f inputs:normal.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.normalMap=b(O),w.normalMap.colorSpace=si,'def Shader "Transform2d_normal"'in S&&y(w.normalMap,S['def Shader "Transform2d_normal"'])}if("float inputs:roughness.connect"in C){const D=C["float inputs:roughness.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.roughness=1,w.roughnessMap=b(O),w.roughnessMap.colorSpace=si,'def Shader "Transform2d_roughness"'in S&&y(w.roughnessMap,S['def Shader "Transform2d_roughness"'])}else"float inputs:roughness"in C&&(w.roughness=parseFloat(C["float inputs:roughness"]));if("float inputs:metallic.connect"in C){const D=C["float inputs:metallic.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.metalness=1,w.metalnessMap=b(O),w.metalnessMap.colorSpace=si,'def Shader "Transform2d_metallic"'in S&&y(w.metalnessMap,S['def Shader "Transform2d_metallic"'])}else"float inputs:metallic"in C&&(w.metalness=parseFloat(C["float inputs:metallic"]));if("float inputs:clearcoat.connect"in C){const D=C["float inputs:clearcoat.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.clearcoat=1,w.clearcoatMap=b(O),w.clearcoatMap.colorSpace=si,'def Shader "Transform2d_clearcoat"'in S&&y(w.clearcoatMap,S['def Shader "Transform2d_clearcoat"'])}else"float inputs:clearcoat"in C&&(w.clearcoat=parseFloat(C["float inputs:clearcoat"]));if("float inputs:clearcoatRoughness.connect"in C){const D=C["float inputs:clearcoatRoughness.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.clearcoatRoughness=1,w.clearcoatRoughnessMap=b(O),w.clearcoatRoughnessMap.colorSpace=si,'def Shader "Transform2d_clearcoatRoughness"'in S&&y(w.clearcoatRoughnessMap,S['def Shader "Transform2d_clearcoatRoughness"'])}else"float inputs:clearcoatRoughness"in C&&(w.clearcoatRoughness=parseFloat(C["float inputs:clearcoatRoughness"]));if("float inputs:ior"in C&&(w.ior=parseFloat(C["float inputs:ior"])),"float inputs:occlusion.connect"in C){const D=C["float inputs:occlusion.connect"],O=v(h,/(\w+).output/.exec(D)[1]);w.aoMap=b(O),w.aoMap.colorSpace=si,'def Shader "Transform2d_occlusion"'in S&&y(w.aoMap,S['def Shader "Transform2d_occlusion"'])}}if('def Shader "diffuseColor_texture"'in S){const C=S['def Shader "diffuseColor_texture"'];w.map=b(C),w.map.colorSpace=vt}if('def Shader "normal_texture"'in S){const C=S['def Shader "normal_texture"'];w.normalMap=b(C),w.normalMap.colorSpace=si}}return w}function v(S,w){for(const C in S){const D=S[C];if(C.startsWith(`def Shader "${w}"`))return D;if(typeof D=="object"){const O=v(D,w);if(O)return O}}}function b(S){if("asset inputs:file"in S){const w=S["asset inputs:file"].replace(/@*/g,""),D=new to().load(o[w]),O={'"clamp"':ui,'"mirror"':Zr,'"repeat"':Bn};return"token inputs:wrapS"in S&&(D.wrapS=O[S["token inputs:wrapS"]]),"token inputs:wrapT"in S&&(D.wrapT=O[S["token inputs:wrapT"]]),D}return null}function T(S){const w=p(u(S)),C=_(A(S)),D=w?new ye(w,C):new ft;if("matrix4d xformOp:transform"in S){const O=JSON.parse("["+S["matrix4d xformOp:transform"].replace(/[()]*/g,"")+"]");D.matrix.fromArray(O),D.matrix.decompose(D.position,D.quaternion,D.scale)}return D}function E(S,w){for(const C in S)if(C.startsWith("def Scope"))E(S[C],w);else if(C.startsWith("def Xform")){const D=T(S[C]);/def Xform "(\w+)"/.test(C)&&(D.name=/def Xform "(\w+)"/.exec(C)[1]),w.add(D),E(S[C],D)}}const M=new Ri;return E(h,M),M}}const bs=new se;class nI extends li{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,n){const s=this,a=new Zt(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}setPropertyNameMapping(e){this.propertyNameMapping=e}setCustomPropertyNameMapping(e){this.customPropertyMapping=e}parse(e){function t(g,y=0){const _=/^ply([\s\S]*)end_header(\r\n|\r|\n)/;let v="";const b=_.exec(g);b!==null&&(v=b[1]);const T={comments:[],elements:[],headerLength:y,objInfo:""},E=v.split(/\r\n|\r|\n/);let M;function S(w,C){const D={type:w[0]};return D.type==="list"?(D.name=w[3],D.countType=w[1],D.itemType=w[2]):D.name=w[1],D.name in C&&(D.name=C[D.name]),D}for(let w=0;w<E.length;w++){let C=E[w];if(C=C.trim(),C==="")continue;const D=C.split(/\s+/),O=D.shift();switch(C=D.join(" "),O){case"format":T.format=D[0],T.version=D[1];break;case"comment":T.comments.push(C);break;case"element":M!==void 0&&T.elements.push(M),M={},M.name=D[0],M.count=parseInt(D[1]),M.properties=[];break;case"property":M.properties.push(S(D,A.propertyNameMapping));break;case"obj_info":T.objInfo=C;break;default:console.log("unhandled",O,D)}}return M!==void 0&&T.elements.push(M),T}function i(g,y){switch(y){case"char":case"uchar":case"short":case"ushort":case"int":case"uint":case"int8":case"uint8":case"int16":case"uint16":case"int32":case"uint32":return parseInt(g);case"float":case"double":case"float32":case"float64":return parseFloat(g)}}function n(g,y){const _={};for(let v=0;v<g.length;v++){if(y.empty())return null;if(g[v].type==="list"){const b=[],T=i(y.next(),g[v].countType);for(let E=0;E<T;E++){if(y.empty())return null;b.push(i(y.next(),g[v].itemType))}_[g[v].name]=b}else _[g[v].name]=i(y.next(),g[v].type)}return _}function s(){const g={indices:[],vertices:[],normals:[],uvs:[],faceVertexUvs:[],colors:[],faceVertexColors:[]};for(const y of Object.keys(A.customPropertyMapping))g[y]=[];return g}function a(g){const y=g.map(v=>v.name);function _(v){for(let b=0,T=v.length;b<T;b++){const E=v[b];if(y.includes(E))return E}return null}return{attrX:_(["x","px","posx"])||"x",attrY:_(["y","py","posy"])||"y",attrZ:_(["z","pz","posz"])||"z",attrNX:_(["nx","normalx"]),attrNY:_(["ny","normaly"]),attrNZ:_(["nz","normalz"]),attrS:_(["s","u","texture_u","tx"]),attrT:_(["t","v","texture_v","ty"]),attrR:_(["red","diffuse_red","r","diffuse_r"]),attrG:_(["green","diffuse_green","g","diffuse_g"]),attrB:_(["blue","diffuse_blue","b","diffuse_b"])}}function o(g,y){const _=s(),v=/end_header\s+(\S[\s\S]*\S|\S)\s*$/;let b,T;(T=v.exec(g))!==null?b=T[1].split(/\s+/):b=[];const E=new T5(b);e:for(let M=0;M<y.elements.length;M++){const S=y.elements[M],w=a(S.properties);for(let C=0;C<S.count;C++){const D=n(S.properties,E);if(!D)break e;c(_,S.name,D,w)}}return l(_)}function l(g){let y=new $e;g.indices.length>0&&y.setIndex(g.indices),y.setAttribute("position",new Me(g.vertices,3)),g.normals.length>0&&y.setAttribute("normal",new Me(g.normals,3)),g.uvs.length>0&&y.setAttribute("uv",new Me(g.uvs,2)),g.colors.length>0&&y.setAttribute("color",new Me(g.colors,3)),(g.faceVertexUvs.length>0||g.faceVertexColors.length>0)&&(y=y.toNonIndexed(),g.faceVertexUvs.length>0&&y.setAttribute("uv",new Me(g.faceVertexUvs,2)),g.faceVertexColors.length>0&&y.setAttribute("color",new Me(g.faceVertexColors,3)));for(const _ of Object.keys(A.customPropertyMapping))g[_].length>0&&y.setAttribute(_,new Me(g[_],A.customPropertyMapping[_].length));return y.computeBoundingSphere(),y}function c(g,y,_,v){if(y==="vertex"){g.vertices.push(_[v.attrX],_[v.attrY],_[v.attrZ]),v.attrNX!==null&&v.attrNY!==null&&v.attrNZ!==null&&g.normals.push(_[v.attrNX],_[v.attrNY],_[v.attrNZ]),v.attrS!==null&&v.attrT!==null&&g.uvs.push(_[v.attrS],_[v.attrT]),v.attrR!==null&&v.attrG!==null&&v.attrB!==null&&(bs.setRGB(_[v.attrR]/255,_[v.attrG]/255,_[v.attrB]/255).convertSRGBToLinear(),g.colors.push(bs.r,bs.g,bs.b));for(const b of Object.keys(A.customPropertyMapping))for(const T of A.customPropertyMapping[b])g[b].push(_[T])}else if(y==="face"){const b=_.vertex_indices||_.vertex_index,T=_.texcoord;b.length===3?(g.indices.push(b[0],b[1],b[2]),T&&T.length===6&&(g.faceVertexUvs.push(T[0],T[1]),g.faceVertexUvs.push(T[2],T[3]),g.faceVertexUvs.push(T[4],T[5]))):b.length===4&&(g.indices.push(b[0],b[1],b[3]),g.indices.push(b[1],b[2],b[3])),v.attrR!==null&&v.attrG!==null&&v.attrB!==null&&(bs.setRGB(_[v.attrR]/255,_[v.attrG]/255,_[v.attrB]/255).convertSRGBToLinear(),g.faceVertexColors.push(bs.r,bs.g,bs.b),g.faceVertexColors.push(bs.r,bs.g,bs.b),g.faceVertexColors.push(bs.r,bs.g,bs.b))}}function h(g,y){const _={};let v=0;for(let b=0;b<y.length;b++){const T=y[b],E=T.valueReader;if(T.type==="list"){const M=[],S=T.countReader.read(g+v);v+=T.countReader.size;for(let w=0;w<S;w++)M.push(E.read(g+v)),v+=E.size;_[T.name]=M}else _[T.name]=E.read(g+v),v+=E.size}return[_,v]}function u(g,y,_){function v(b,T,E){switch(T){case"int8":case"char":return{read:M=>b.getInt8(M),size:1};case"uint8":case"uchar":return{read:M=>b.getUint8(M),size:1};case"int16":case"short":return{read:M=>b.getInt16(M,E),size:2};case"uint16":case"ushort":return{read:M=>b.getUint16(M,E),size:2};case"int32":case"int":return{read:M=>b.getInt32(M,E),size:4};case"uint32":case"uint":return{read:M=>b.getUint32(M,E),size:4};case"float32":case"float":return{read:M=>b.getFloat32(M,E),size:4};case"float64":case"double":return{read:M=>b.getFloat64(M,E),size:8}}}for(let b=0,T=g.length;b<T;b++){const E=g[b];E.type==="list"?(E.countReader=v(y,E.countType,_),E.valueReader=v(y,E.itemType,_)):E.valueReader=v(y,E.type,_)}}function d(g,y){const _=s(),v=y.format==="binary_little_endian",b=new DataView(g,y.headerLength);let T,E=0;for(let M=0;M<y.elements.length;M++){const S=y.elements[M],w=S.properties,C=a(w);u(w,b,v);for(let D=0;D<S.count;D++){T=h(E,w),E+=T[1];const O=T[0];c(_,S.name,O,C)}}return l(_)}function p(g){let y=0,_=!0,v="";const b=[],T=new TextDecoder().decode(g.subarray(0,5)),E=/^ply\r\n/.test(T);do{const M=String.fromCharCode(g[y++]);M!==`
`&&M!=="\r"?v+=M:(v==="end_header"&&(_=!1),v!==""&&(b.push(v),v=""))}while(_&&y<g.length);return E===!0&&y++,{headerText:b.join("\r")+"\r",headerLength:y}}let m;const A=this;if(e instanceof ArrayBuffer){const g=new Uint8Array(e),{headerText:y,headerLength:_}=p(g),v=t(y,_);if(v.format==="ascii"){const b=new TextDecoder().decode(g);m=o(b,v)}else m=d(e,v)}else m=o(e,t(e));return m}}class T5{constructor(e){this.arr=e,this.i=0}empty(){return this.i>=this.arr.length}next(){return this.arr[this.i++]}}class sI extends li{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new Zt(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){function t(c){const h=new DataView(c),u=32/8*3+32/8*3*3+16/8,d=h.getUint32(80,!0);if(80+32/8+d*u===h.byteLength)return!0;const m=[115,111,108,105,100];for(let A=0;A<5;A++)if(i(m,h,A))return!1;return!0}function i(c,h,u){for(let d=0,p=c.length;d<p;d++)if(c[d]!==h.getUint8(u+d))return!1;return!0}function n(c){const h=new DataView(c),u=h.getUint32(80,!0);let d,p,m,A=!1,g,y,_,v,b;for(let D=0;D<70;D++)h.getUint32(D,!1)==1129270351&&h.getUint8(D+4)==82&&h.getUint8(D+5)==61&&(A=!0,g=new Float32Array(u*3*3),y=h.getUint8(D+6)/255,_=h.getUint8(D+7)/255,v=h.getUint8(D+8)/255,b=h.getUint8(D+9)/255);const T=84,E=50,M=new $e,S=new Float32Array(u*3*3),w=new Float32Array(u*3*3),C=new se;for(let D=0;D<u;D++){const O=T+D*E,F=h.getFloat32(O,!0),G=h.getFloat32(O+4,!0),j=h.getFloat32(O+8,!0);if(A){const W=h.getUint16(O+48,!0);(W&32768)===0?(d=(W&31)/31,p=(W>>5&31)/31,m=(W>>10&31)/31):(d=y,p=_,m=v)}for(let W=1;W<=3;W++){const K=O+W*12,q=D*3*3+(W-1)*3;S[q]=h.getFloat32(K,!0),S[q+1]=h.getFloat32(K+4,!0),S[q+2]=h.getFloat32(K+8,!0),w[q]=F,w[q+1]=G,w[q+2]=j,A&&(C.set(d,p,m).convertSRGBToLinear(),g[q]=C.r,g[q+1]=C.g,g[q+2]=C.b)}}return M.setAttribute("position",new Xe(S,3)),M.setAttribute("normal",new Xe(w,3)),A&&(M.setAttribute("color",new Xe(g,3)),M.hasColors=!0,M.alpha=b),M}function s(c){const h=new $e,u=/solid([\s\S]*?)endsolid/g,d=/facet([\s\S]*?)endfacet/g,p=/solid\s(.+)/;let m=0;const A=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,g=new RegExp("vertex"+A+A+A,"g"),y=new RegExp("normal"+A+A+A,"g"),_=[],v=[],b=[],T=new x;let E,M=0,S=0,w=0;for(;(E=u.exec(c))!==null;){S=w;const C=E[0],D=(E=p.exec(C))!==null?E[1]:"";for(b.push(D);(E=d.exec(C))!==null;){let G=0,j=0;const W=E[0];for(;(E=y.exec(W))!==null;)T.x=parseFloat(E[1]),T.y=parseFloat(E[2]),T.z=parseFloat(E[3]),j++;for(;(E=g.exec(W))!==null;)_.push(parseFloat(E[1]),parseFloat(E[2]),parseFloat(E[3])),v.push(T.x,T.y,T.z),G++,w++;j!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+m),G!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+m),m++}const O=S,F=w-S;h.userData.groupNames=b,h.addGroup(O,F,M),M++}return h.setAttribute("position",new Me(_,3)),h.setAttribute("normal",new Me(v,3)),h}function a(c){return typeof c!="string"?new TextDecoder().decode(c):c}function o(c){if(typeof c=="string"){const h=new Uint8Array(c.length);for(let u=0;u<c.length;u++)h[u]=c.charCodeAt(u)&255;return h.buffer||h}else return c}const l=o(e);return t(l)?n(l):s(a(e))}}class I5{constructor(e,t,i){this.variables=[],this.currentTextureIndex=0;let n=zt;const s=new qa,a=new Ac;a.position.z=1;const o={passThruTexture:{value:null}},l=u(p(),o),c=new ye(new Er(2,2),l);s.add(c),this.setDataType=function(m){return n=m,this},this.addVariable=function(m,A,g){const y=this.createShaderMaterial(A),_={name:m,initialValueTexture:g,material:y,dependencies:null,renderTargets:[],wrapS:null,wrapT:null,minFilter:pi,magFilter:pi};return this.variables.push(_),_},this.setVariableDependencies=function(m,A){m.dependencies=A},this.init=function(){if(i.capabilities.maxVertexTextures===0)return"No support for vertex shader textures.";for(let m=0;m<this.variables.length;m++){const A=this.variables[m];A.renderTargets[0]=this.createRenderTarget(e,t,A.wrapS,A.wrapT,A.minFilter,A.magFilter),A.renderTargets[1]=this.createRenderTarget(e,t,A.wrapS,A.wrapT,A.minFilter,A.magFilter),this.renderTexture(A.initialValueTexture,A.renderTargets[0]),this.renderTexture(A.initialValueTexture,A.renderTargets[1]);const g=A.material,y=g.uniforms;if(A.dependencies!==null)for(let _=0;_<A.dependencies.length;_++){const v=A.dependencies[_];if(v.name!==A.name){let b=!1;for(let T=0;T<this.variables.length;T++)if(v.name===this.variables[T].name){b=!0;break}if(!b)return"Variable dependency not found. Variable="+A.name+", dependency="+v.name}y[v.name]={value:null},g.fragmentShader=`
uniform sampler2D `+v.name+`;
`+g.fragmentShader}}return this.currentTextureIndex=0,null},this.compute=function(){const m=this.currentTextureIndex,A=this.currentTextureIndex===0?1:0;for(let g=0,y=this.variables.length;g<y;g++){const _=this.variables[g];if(_.dependencies!==null){const v=_.material.uniforms;for(let b=0,T=_.dependencies.length;b<T;b++){const E=_.dependencies[b];v[E.name].value=E.renderTargets[m].texture}}this.doRenderTarget(_.material,_.renderTargets[A])}this.currentTextureIndex=A},this.getCurrentRenderTarget=function(m){return m.renderTargets[this.currentTextureIndex]},this.getAlternateRenderTarget=function(m){return m.renderTargets[this.currentTextureIndex===0?1:0]},this.dispose=function(){c.geometry.dispose(),c.material.dispose();const m=this.variables;for(let A=0;A<m.length;A++){const g=m[A];g.initialValueTexture&&g.initialValueTexture.dispose();const y=g.renderTargets;for(let _=0;_<y.length;_++)y[_].dispose()}};function h(m){m.defines.resolution="vec2( "+e.toFixed(1)+", "+t.toFixed(1)+" )"}this.addResolutionDefine=h;function u(m,A){A=A||{};const g=new nn({name:"GPUComputationShader",uniforms:A,vertexShader:d(),fragmentShader:m});return h(g),g}this.createShaderMaterial=u,this.createRenderTarget=function(m,A,g,y,_,v){return m=m||e,A=A||t,g=g||ui,y=y||ui,_=_||pi,v=v||pi,new ps(m,A,{wrapS:g,wrapT:y,minFilter:_,magFilter:v,format:Kt,type:n,depthBuffer:!1})},this.createTexture=function(){const m=new Float32Array(e*t*4),A=new As(m,e,t,Kt,zt);return A.needsUpdate=!0,A},this.renderTexture=function(m,A){o.passThruTexture.value=m,this.doRenderTarget(l,A),o.passThruTexture.value=null},this.doRenderTarget=function(m,A){const g=i.getRenderTarget(),y=i.xr.enabled,_=i.shadowMap.autoUpdate;i.xr.enabled=!1,i.shadowMap.autoUpdate=!1,c.material=m,i.setRenderTarget(A),i.render(s,a),c.material=l,i.xr.enabled=y,i.shadowMap.autoUpdate=_,i.setRenderTarget(g)};function d(){return`void main()	{

	gl_Position = vec4( position, 1.0 );

}
`}function p(){return`uniform sampler2D passThruTexture;

void main() {

	vec2 uv = gl_FragCoord.xy / resolution.xy;

	gl_FragColor = texture2D( passThruTexture, uv );

}
`}}}const ki=new ns,_g=new x,rI=new $,aI=new $,oI=new $;class P5{constructor(e){this.geometry=e.geometry,this.randomFunction=Math.random,this.indexAttribute=this.geometry.index,this.positionAttribute=this.geometry.getAttribute("position"),this.normalAttribute=this.geometry.getAttribute("normal"),this.colorAttribute=this.geometry.getAttribute("color"),this.uvAttribute=this.geometry.getAttribute("uv"),this.weightAttribute=null,this.distribution=null}setWeightAttribute(e){return this.weightAttribute=e?this.geometry.getAttribute(e):null,this}build(){const e=this.indexAttribute,t=this.positionAttribute,i=this.weightAttribute,n=e?e.count/3:t.count/3,s=new Float32Array(n);for(let l=0;l<n;l++){let c=1,h=3*l,u=3*l+1,d=3*l+2;e&&(h=e.getX(h),u=e.getX(u),d=e.getX(d)),i&&(c=i.getX(h)+i.getX(u)+i.getX(d)),ki.a.fromBufferAttribute(t,h),ki.b.fromBufferAttribute(t,u),ki.c.fromBufferAttribute(t,d),c*=ki.getArea(),s[l]=c}const a=new Float32Array(n);let o=0;for(let l=0;l<n;l++)o+=s[l],a[l]=o;return this.distribution=a,this}setRandomGenerator(e){return this.randomFunction=e,this}sample(e,t,i,n){const s=this.sampleFaceIndex();return this.sampleFace(s,e,t,i,n)}sampleFaceIndex(){const e=this.distribution[this.distribution.length-1];return this.binarySearch(this.randomFunction()*e)}binarySearch(e){const t=this.distribution;let i=0,n=t.length-1,s=-1;for(;i<=n;){const a=Math.ceil((i+n)/2);if(a===0||t[a-1]<=e&&t[a]>e){s=a;break}else e<t[a]?n=a-1:i=a+1}return s}sampleFace(e,t,i,n,s){let a=this.randomFunction(),o=this.randomFunction();a+o>1&&(a=1-a,o=1-o);const l=this.indexAttribute;let c=e*3,h=e*3+1,u=e*3+2;return l&&(c=l.getX(c),h=l.getX(h),u=l.getX(u)),ki.a.fromBufferAttribute(this.positionAttribute,c),ki.b.fromBufferAttribute(this.positionAttribute,h),ki.c.fromBufferAttribute(this.positionAttribute,u),t.set(0,0,0).addScaledVector(ki.a,a).addScaledVector(ki.b,o).addScaledVector(ki.c,1-(a+o)),i!==void 0&&(this.normalAttribute!==void 0?(ki.a.fromBufferAttribute(this.normalAttribute,c),ki.b.fromBufferAttribute(this.normalAttribute,h),ki.c.fromBufferAttribute(this.normalAttribute,u),i.set(0,0,0).addScaledVector(ki.a,a).addScaledVector(ki.b,o).addScaledVector(ki.c,1-(a+o)).normalize()):ki.getNormal(i)),n!==void 0&&this.colorAttribute!==void 0&&(ki.a.fromBufferAttribute(this.colorAttribute,c),ki.b.fromBufferAttribute(this.colorAttribute,h),ki.c.fromBufferAttribute(this.colorAttribute,u),_g.set(0,0,0).addScaledVector(ki.a,a).addScaledVector(ki.b,o).addScaledVector(ki.c,1-(a+o)),n.r=_g.x,n.g=_g.y,n.b=_g.z),s!==void 0&&this.uvAttribute!==void 0&&(rI.fromBufferAttribute(this.uvAttribute,c),aI.fromBufferAttribute(this.uvAttribute,h),oI.fromBufferAttribute(this.uvAttribute,u),s.set(0,0).addScaledVector(rI,a).addScaledVector(aI,o).addScaledVector(oI,1-(a+o))),this}}const bg=0,D5=1,R5=new x,lI=new Gy,f_=new Ts,cI=new x,wg=new ns;class B5{constructor(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new p_,this.unassigned=new p_,this.vertices=[]}setFromPoints(e){if(e.length>=4){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.vertices.push(new hI(e[t]));this.compute()}return this}setFromObject(e){const t=[];return e.updateMatrixWorld(!0),e.traverse(function(i){const n=i.geometry;if(n!==void 0){const s=n.attributes.position;if(s!==void 0)for(let a=0,o=s.count;a<o;a++){const l=new x;l.fromBufferAttribute(s,a).applyMatrix4(i.matrixWorld),t.push(l)}}}),this.setFromPoints(t)}containsPoint(e){const t=this.faces;for(let i=0,n=t.length;i<n;i++)if(t[i].distanceToPoint(e)>this.tolerance)return!1;return!0}intersectRay(e,t){const i=this.faces;let n=-1/0,s=1/0;for(let a=0,o=i.length;a<o;a++){const l=i[a],c=l.distanceToPoint(e.origin),h=l.normal.dot(e.direction);if(c>0&&h>=0)return null;const u=h!==0?-c/h:0;if(!(u<=0)&&(h>0?s=Math.min(u,s):n=Math.max(u,n),n>s))return null}return n!==-1/0?e.at(n,t):e.at(s,t),t}intersectsRay(e){return this.intersectRay(e,R5)!==null}makeEmpty(){return this.faces=[],this.vertices=[],this}addVertexToFace(e,t){return e.face=t,t.outside===null?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this}removeVertexFromFace(e,t){return e===t.outside&&(e.next!==null&&e.next.face===t?t.outside=e.next:t.outside=null),this.assigned.remove(e),this}removeAllVerticesFromFace(e){if(e.outside!==null){const t=e.outside;let i=e.outside;for(;i.next!==null&&i.next.face===e;)i=i.next;return this.assigned.removeSubList(t,i),t.prev=i.next=null,e.outside=null,t}}deleteFaceVertices(e,t){const i=this.removeAllVerticesFromFace(e);if(i!==void 0)if(t===void 0)this.unassigned.appendChain(i);else{let n=i;do{const s=n.next;t.distanceToPoint(n.point)>this.tolerance?this.addVertexToFace(n,t):this.unassigned.append(n),n=s}while(n!==null)}return this}resolveUnassignedPoints(e){if(this.unassigned.isEmpty()===!1){let t=this.unassigned.first();do{const i=t.next;let n=this.tolerance,s=null;for(let a=0;a<e.length;a++){const o=e[a];if(o.mark===bg){const l=o.distanceToPoint(t.point);if(l>n&&(n=l,s=o),n>1e3*this.tolerance)break}}s!==null&&this.addVertexToFace(t,s),t=i}while(t!==null)}return this}computeExtremes(){const e=new x,t=new x,i=[],n=[];for(let s=0;s<3;s++)i[s]=n[s]=this.vertices[0];e.copy(this.vertices[0].point),t.copy(this.vertices[0].point);for(let s=0,a=this.vertices.length;s<a;s++){const o=this.vertices[s],l=o.point;for(let c=0;c<3;c++)l.getComponent(c)<e.getComponent(c)&&(e.setComponent(c,l.getComponent(c)),i[c]=o);for(let c=0;c<3;c++)l.getComponent(c)>t.getComponent(c)&&(t.setComponent(c,l.getComponent(c)),n[c]=o)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(e.x),Math.abs(t.x))+Math.max(Math.abs(e.y),Math.abs(t.y))+Math.max(Math.abs(e.z),Math.abs(t.z))),{min:i,max:n}}computeInitialHull(){const e=this.vertices,t=this.computeExtremes(),i=t.min,n=t.max;let s=0,a=0;for(let d=0;d<3;d++){const p=n[d].point.getComponent(d)-i[d].point.getComponent(d);p>s&&(s=p,a=d)}const o=i[a],l=n[a];let c,h;s=0,lI.set(o.point,l.point);for(let d=0,p=this.vertices.length;d<p;d++){const m=e[d];if(m!==o&&m!==l){lI.closestPointToPoint(m.point,!0,cI);const A=cI.distanceToSquared(m.point);A>s&&(s=A,c=m)}}s=-1,f_.setFromCoplanarPoints(o.point,l.point,c.point);for(let d=0,p=this.vertices.length;d<p;d++){const m=e[d];if(m!==o&&m!==l&&m!==c){const A=Math.abs(f_.distanceToPoint(m.point));A>s&&(s=A,h=m)}}const u=[];if(f_.distanceToPoint(h.point)<0){u.push(Zs.create(o,l,c),Zs.create(h,l,o),Zs.create(h,c,l),Zs.create(h,o,c));for(let d=0;d<3;d++){const p=(d+1)%3;u[d+1].getEdge(2).setTwin(u[0].getEdge(p)),u[d+1].getEdge(1).setTwin(u[p+1].getEdge(0))}}else{u.push(Zs.create(o,c,l),Zs.create(h,o,l),Zs.create(h,l,c),Zs.create(h,c,o));for(let d=0;d<3;d++){const p=(d+1)%3;u[d+1].getEdge(2).setTwin(u[0].getEdge((3-d)%3)),u[d+1].getEdge(0).setTwin(u[p+1].getEdge(1))}}for(let d=0;d<4;d++)this.faces.push(u[d]);for(let d=0,p=e.length;d<p;d++){const m=e[d];if(m!==o&&m!==l&&m!==c&&m!==h){s=this.tolerance;let A=null;for(let g=0;g<4;g++){const y=this.faces[g].distanceToPoint(m.point);y>s&&(s=y,A=this.faces[g])}A!==null&&this.addVertexToFace(m,A)}}return this}reindexFaces(){const e=[];for(let t=0;t<this.faces.length;t++){const i=this.faces[t];i.mark===bg&&e.push(i)}return this.faces=e,this}nextVertexToAdd(){if(this.assigned.isEmpty()===!1){let e,t=0;const i=this.assigned.first().face;let n=i.outside;do{const s=i.distanceToPoint(n.point);s>t&&(t=s,e=n),n=n.next}while(n!==null&&n.face===i);return e}}computeHorizon(e,t,i,n){this.deleteFaceVertices(i),i.mark=D5;let s;t===null?s=t=i.getEdge(0):s=t.next;do{const a=s.twin,o=a.face;o.mark===bg&&(o.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,a,o,n):n.push(s)),s=s.next}while(s!==t);return this}addAdjoiningFace(e,t){const i=Zs.create(e,t.tail(),t.head());return this.faces.push(i),i.getEdge(-1).setTwin(t.twin),i.getEdge(0)}addNewFaces(e,t){this.newFaces=[];let i=null,n=null;for(let s=0;s<t.length;s++){const a=t[s],o=this.addAdjoiningFace(e,a);i===null?i=o:o.next.setTwin(n),this.newFaces.push(o.face),n=o}return i.next.setTwin(n),this}addVertexToHull(e){const t=[];return this.unassigned.clear(),this.removeVertexFromFace(e,e.face),this.computeHorizon(e.point,null,e.face,t),this.addNewFaces(e,t),this.resolveUnassignedPoints(this.newFaces),this}cleanup(){return this.assigned.clear(),this.unassigned.clear(),this.newFaces=[],this}compute(){let e;for(this.computeInitialHull();(e=this.nextVertexToAdd())!==void 0;)this.addVertexToHull(e);return this.reindexFaces(),this.cleanup(),this}}class Zs{constructor(){this.normal=new x,this.midpoint=new x,this.area=0,this.constant=0,this.outside=null,this.mark=bg,this.edge=null}static create(e,t,i){const n=new Zs,s=new Cg(e,n),a=new Cg(t,n),o=new Cg(i,n);return s.next=o.prev=a,a.next=s.prev=o,o.next=a.prev=s,n.edge=s,n.compute()}getEdge(e){let t=this.edge;for(;e>0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t}compute(){const e=this.edge.tail(),t=this.edge.head(),i=this.edge.next.head();return wg.set(e.point,t.point,i.point),wg.getNormal(this.normal),wg.getMidpoint(this.midpoint),this.area=wg.getArea(),this.constant=this.normal.dot(this.midpoint),this}distanceToPoint(e){return this.normal.dot(e)-this.constant}}class Cg{constructor(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){const e=this.head(),t=this.tail();return t!==null?t.point.distanceTo(e.point):-1}lengthSquared(){const e=this.head(),t=this.tail();return t!==null?t.point.distanceToSquared(e.point):-1}setTwin(e){return this.twin=e,e.twin=this,this}}class hI{constructor(e){this.point=e,this.prev=null,this.next=null,this.face=null}}class p_{constructor(){this.head=null,this.tail=null}first(){return this.head}last(){return this.tail}clear(){return this.head=this.tail=null,this}insertBefore(e,t){return t.prev=e.prev,t.next=e,t.prev===null?this.head=t:t.prev.next=t,e.prev=t,this}insertAfter(e,t){return t.prev=e,t.next=e.next,t.next===null?this.tail=t:t.next.prev=t,e.next=t,this}append(e){return this.head===null?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this}appendChain(e){for(this.head===null?this.head=e:this.tail.next=e,e.prev=this.tail;e.next!==null;)e=e.next;return this.tail=e,this}remove(e){return e.prev===null?this.head=e.next:e.prev.next=e.next,e.next===null?this.tail=e.prev:e.next.prev=e.prev,this}removeSubList(e,t){return e.prev===null?this.head=t.next:e.prev.next=t.next,t.next===null?this.tail=e.prev:t.next.prev=e.prev,this}isEmpty(){return this.head===null}}class Pl{constructor(){this.toJSON=null}onAdded(e){e.assetManager.importer.addImporter(this._importer)}onRemove(e){e.assetManager.importer.removeImporter(this._importer)}dispose(){}}var L5=Object.defineProperty,O5=Object.getOwnPropertyDescriptor,Ta=(r,e,t,i)=>{for(var n=i>1?void 0:i?O5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&L5(e,t,n),n};f.BaseGroundPlugin=class extends pt{constructor(){super(),this._transformNeedRefresh=!0,this.visible=!0,this.size=8,this.yOffset=0,this.renderToDepth=!0,this.tonemapGround=!0,this.limitCameraAboveGround=!1,this.autoAdjustTransform=!0,this.enableRefreshTransform=!0,this._cameraLimitsSet=!1,this._cameraLastMaxPolarAngle=Math.PI,this.useModelBounds=!0,this._refreshMaterial=this._refreshMaterial.bind(this),this._refreshTransform=this._refreshTransform.bind(this),this._refreshCameraLimits=this._refreshCameraLimits.bind(this),this.refresh=this.refresh.bind(this),this._refresh2=this._refresh2.bind(this),this._onSceneUpdate=this._onSceneUpdate.bind(this),this._preRender=this._preRender.bind(this),this._postFrame=this._postFrame.bind(this),this._geometry=ri.upgradeGeometry.call(new Er(1,1,1,1)),this._geometry.attributes.uv2=this._geometry.attributes.uv.clone(),this._geometry.attributes.uv2.needsUpdate=!0,this._mesh=this._createMesh(),this._mesh.userData.physicsMass=0,this._mesh.userData.physicsBodyType="static",this._mesh.userData.userSelectable=!1,this._mesh.userData.isGroundMesh=!0,this._mesh.castShadow=!0,this._mesh.receiveShadow=!0,this._mesh.name||(this._mesh.name="Ground Plane"),this._mesh.visible=!1,this._defaultMaterial=this._mesh.material,this.refresh()}get enabled(){return this.visible}set enabled(e){this.visible=e}onAdded(e){super.onAdded(e),e.scene.addObject(this._mesh,{addToRoot:!0}),e.scene.addEventListener("sceneUpdate",this._onSceneUpdate),e.scene.addEventListener("addSceneObject",this._onSceneUpdate),e.addEventListener("preRender",this._preRender),e.addEventListener("postFrame",this._postFrame),this.refresh()}onRemove(e){return this._mesh?.dispose(!0),this._removeMaterial(),e.scene.removeEventListener("sceneUpdate",this._onSceneUpdate),e.scene.removeEventListener("addSceneObject",this._onSceneUpdate),e.removeEventListener("postFrame",this._postFrame),e.removeEventListener("preRender",this._preRender),super.onRemove(e)}_postFrame(){this._transformNeedRefresh&&this._refreshTransform(),this._viewer}_preRender(){this._viewer}dispose(){this._removeMaterial(),this._geometry.dispose(),this._material?.dispose(),this._mesh?.dispose?.(),super.dispose()}_removeMaterial(){!this._material||this._material===this._defaultMaterial||(this._material.userData.renderToDepth=this._material.userData.__renderToDepth,this._material.userData.__renderToDepth=void 0,this._material=this._defaultMaterial)}_onSceneUpdate(e){e?.object?.assetType==="widget"||e?.object?.userData?.isWidgetRoot||e?.geometryChanged!==!1&&e?.updateGround!==!1&&this.refreshTransform()}refreshTransform(){this.enableRefreshTransform&&(this._transformNeedRefresh=!0)}refresh(){this._viewer&&(this._refreshMaterial(),this.refreshTransform(),this._refreshCameraLimits())}_refresh2(){this.refresh()}_refreshCameraLimits(){const e=this._viewer?.scene.mainCamera.controls;if(e){if(e.maxPolarAngle===void 0){console.warn("refreshCameraLimits only available with orbit controls.");return}this.limitCameraAboveGround?(this._cameraLimitsSet||(this._cameraLastMaxPolarAngle=e.maxPolarAngle),e.maxPolarAngle=Math.PI/2,this._cameraLimitsSet=!0):this._cameraLimitsSet&&(e.maxPolarAngle=this._cameraLastMaxPolarAngle,this._cameraLimitsSet=!1)}}_refreshTransform(){if(!this._mesh||!this._viewer)return!1;let e=!1;if(this.visible!==this._mesh.visible&&(this._mesh.visible=this.visible,e=!0),this.isDisabled())return e&&this._viewer?.scene.setDirty(),!1;if(this.autoAdjustTransform){this._mesh.userData.bboxVisible=!1;const t=this.useModelBounds?this._viewer.scene.getModelBounds(!0,!0,!0):this._viewer.scene.getBounds(!0,!0,!0);this._mesh.userData.bboxVisible=!0;const i=t.getCenter(new x).sub(new x(0,t.getSize(new x).y/2+this.yOffset,0));e=e||i.clone().sub(this._mesh.position).length()>1e-4,e&&this._mesh.position.copy(i)}return e=e||Math.abs(this._mesh.scale.x-this.size)>1e-4,e&&(this._mesh.scale.setScalar(this.size),this._mesh.setRotationFromEuler(new Tt(-Math.PI/2,0,this._mesh.rotation.z)),this._mesh.matrixWorldNeedsUpdate=!0,this._mesh.setDirty({refreshScene:!1,source:f.BaseGroundPlugin.PluginType})),this._mesh.visible=this.size>=1e-4,this._transformNeedRefresh=!1,!0}_createMesh(e){return e?e.geometry=this._geometry:e=new zm(this._geometry,this._createMaterial()),e}setGeometry(e){e?this._geometry&&this._geometry.dispose():e=this._geometry,e&&(this._geometry=e,ri.upgradeGeometry.call(this._geometry),this._geometry.attributes.uv2||(this._geometry.attributes.uv2=this._geometry.attributes.uv.clone(),this._geometry.attributes.uv2.needsUpdate=!0),this._mesh&&(this._mesh.geometry=this._geometry))}_createMaterial(e){return e||(e=new ai({name:"BaseGroundMaterial",color:16777215,roughness:.8,metalness:.5})),e.userData.runtimeMaterial=!0,e}_refreshMaterial(){this._viewer&&(this.isDisabled()||(this._material||(this._material=this._defaultMaterial,this._viewer.scene.setDirty()),this._material.userData.__renderToDepth===void 0&&(this._material.userData.__renderToDepth=this._material.userData.renderToDepth),this._material.userData.renderToDepth!==this.renderToDepth&&(this._material.userData.renderToDepth=this.renderToDepth),this._material.userData.gBufferData||(this._material.userData.gBufferData={}),this._material.userData.gBufferData.__tonemapEnabled===void 0&&(this._material.userData.gBufferData.__tonemapEnabled=this._material.userData.gBufferData.tonemapEnabled),this._material.userData.gBufferData.tonemapEnabled!==this.tonemapGround&&(this._material.userData.gBufferData.tonemapEnabled=this.tonemapGround),this._viewer.setDirty(this)))}get material(){return this._material}get mesh(){return this._mesh}fromJSON(e,t){return e.options&&console.error("todo: support old webgi v0 file"),super.fromJSON(e,t)?(this.refresh(),this):null}},f.BaseGroundPlugin.PluginType="BaseGroundPlugin",f.BaseGroundPlugin.OldPluginType="Ground",Ta([ae("Visible"),de(f.BaseGroundPlugin.prototype.refreshTransform),z()],f.BaseGroundPlugin.prototype,"visible",2),Ta([Lt("Size"),ei(f.BaseGroundPlugin.prototype._onSceneUpdate),z()],f.BaseGroundPlugin.prototype,"size",2),Ta([Lt("Height (yOffset)"),ei(f.BaseGroundPlugin.prototype._onSceneUpdate),z()],f.BaseGroundPlugin.prototype,"yOffset",2),Ta([ae("Render to Depth"),de(f.BaseGroundPlugin.prototype._refresh2),z()],f.BaseGroundPlugin.prototype,"renderToDepth",2),Ta([ae("Tonemap Ground"),de(f.BaseGroundPlugin.prototype._refresh2),z()],f.BaseGroundPlugin.prototype,"tonemapGround",2),Ta([ae("Limit Camera Above Ground"),de(f.BaseGroundPlugin.prototype._refreshCameraLimits),z()],f.BaseGroundPlugin.prototype,"limitCameraAboveGround",2),Ta([ae("Auto Adjust Transform"),de(f.BaseGroundPlugin.prototype.refreshTransform),z()],f.BaseGroundPlugin.prototype,"autoAdjustTransform",2),Ta([z("material"),Li(),Vt({obj:"mesh",key:"material",allowUndefined:!0})],f.BaseGroundPlugin.prototype,"_material",2),f.BaseGroundPlugin=Ta([gt("Ground Plane")],f.BaseGroundPlugin);class xg extends pt{constructor(){super(...arguments),this.enabled=!0,this.toJSON=void 0,this._cameraChanged=e=>{this._unregisterControls(e.lastCamera),this._registerControls(e.camera)}}onAdded(e){super.onAdded(e),this._registerControls(e.scene.mainCamera),e.scene.addEventListener("mainCameraChange",this._cameraChanged)}onRemove(e){this._unregisterControls(e.scene.mainCamera),e.scene.removeEventListener("mainCameraChange",this._cameraChanged),super.onRemove(e)}_registerControls(e){e?.setControlsCtor?.(this.controlsKey,this._controlsCtor)}_unregisterControls(e){e?.removeControlsCtor?.(this.controlsKey)}}var U5=Object.defineProperty,F5=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&U5(e,t,n),n};const m_=class extends pt{constructor(e,t){super(),this.container=t,this.enabled=!0,this._mainDiv=Pr({id:"assetManager"+e,addToBody:!1,innerHTML:""}),this._contentDiv=Pr({id:"assetManager"+e+"Content",addToBody:!1,innerHTML:""}),this.enabled||(this._mainDiv.style.display="none"),this._mainDiv.appendChild(this._contentDiv),this._onProcessStateUpdate=this._onProcessStateUpdate.bind(this)}_onEnabledChange(){this.enabled||(this._mainDiv.style.display="none")}onAdded(e){super.onAdded(e),(this.container??e.container).appendChild(this._mainDiv),this._updateMainDiv(e.assetManager.processState),e.assetManager.addEventListener("processStateUpdate",this._onProcessStateUpdate)}_onProcessStateUpdate(){this._viewer&&this._updateMainDiv(this._viewer.assetManager.processState)}onRemove(e){return this._mainDiv.remove(),e.assetManager.removeEventListener("processStateUpdate",this._onProcessStateUpdate),super.onRemove(e)}};F5([ae("Enabled"),de(m_.prototype._onEnabledChange),z()],m_.prototype,"enabled");let uI=m_;class dI extends nh{constructor(e,t=120){super({vertexShader:bl.vertexShader,fragmentShader:ma`
                uniform vec4 weight;
                uniform vec4 weight2;
                varying vec2 vUv;
                void main() {
                    vec4 texel = clamp(weight * tDiffuseTexelToLinear ( texture2D( tDiffuse, vUv ) ) + weight2 * tDiffuse2TexelToLinear ( texture2D( tDiffuse2, vUv ) ), vec4(0), vec4(MAX_INTENSITY));
                    gl_FragColor = texel;
                    #include <colorspace_fragment>
                }
            `,uniforms:{tDiffuse:{value:null},tDiffuse2:{value:e},weight:{value:new rt(1,1,1,1)},weight2:{value:new rt(1,1,1,1)}},defines:{MAX_INTENSITY:t}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var N5=Object.defineProperty,k5=Object.getOwnPropertyDescriptor,Vd=(r,e,t,i)=>{for(var n=i>1?void 0:i?k5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&N5(e,t,n),n};f.SSAAPlugin=class extends pt{constructor(e=1){super(),this.enabled=!0,this.rendersPerFrame=1,this.jitterRenderCamera=!0,this.jitterLightCameras=!0,this._hasSetOffsetRC=!1,this._hasSetOffsetLC=!1,this.trackedJitterCameras=new Map,this.dependencies=[f.ProgressivePlugin],this._objectAdd=t=>{const i=t.object;i&&i.shadow&&i.shadow.camera&&i.shadow.mapSize&&this.trackedJitterCameras.set(i.shadow.camera,i.shadow.mapSize)},this._objectRemove=t=>{const i=t.object;if(i&&i.shadow&&i.shadow.camera){const n=i.shadow.camera;this._clearJitter(n),this.trackedJitterCameras.delete(n)}},this._preRender=()=>{const t=this._viewer;if(!t||!this.enabled||t.renderManager.frameCount<=1)return;this.rendersPerFrame=t.rendersPerFrame;const i=t.scene.renderCamera;this.jitterRenderCamera&&this._jitter(i,{width:t.renderManager.renderSize.x*t.renderManager.renderScale,height:t.renderManager.renderSize.y*t.renderManager.renderScale},t.renderManager.frameCount,!0),this.jitterLightCameras&&this.trackedJitterCameras.entries().forEach(n=>this._jitter(...n,t.renderManager.frameCount)),this._hasSetOffsetRC=this.jitterRenderCamera,this._hasSetOffsetLC=this.jitterLightCameras,t.renderManager.resetShadows()},this._postRender=()=>{const t=this._viewer;t&&(this._hasSetOffsetRC&&(this._clearJitter(t.scene.renderCamera),this._hasSetOffsetRC=!1),this._hasSetOffsetLC&&(this.trackedJitterCameras.keys().forEach(i=>this._clearJitter(i)),this._hasSetOffsetLC=!1))},this.jitterOffsets=[{x:0,y:0},{x:-.5,y:0},{x:-.375,y:-.25},{x:-.1875,y:-.125},{x:-.125,y:-.375},{x:.0625,y:-.0625},{x:.125,y:-.3125},{x:.375,y:-.4375},{x:.3125,y:-.1875},{x:.25,y:.0625},{x:.4375,y:.25},{x:.1875,y:.3125},{x:0,y:.4375},{x:-.0625,y:.1875},{x:-.25,y:.375},{x:-.4375,y:.5},{x:-.3125,y:.125}],this.rendersPerFrame=e}onAdded(e){super.onAdded(e),e.addEventListener("preRender",this._preRender),e.addEventListener("postRender",this._postRender),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove)}onRemove(e){return e.removeEventListener("preRender",this._preRender),e.removeEventListener("postRender",this._postRender),e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),super.onRemove(e)}setDirty(){this._viewer&&(this._viewer.rendersPerFrame=this.rendersPerFrame,this._viewer.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame"))}_jitter(e,t,i,n=!1){if(e.userData.disableJitter)return;if(e.userData.__jittered){this._viewer?.console.warn("SSAAPlugin: Camera already jittered");return}const s={...this.jitterOffsets[i%this.jitterOffsets.length]},a=e.aspect,o=e.autoAspect||!n?t.height:t.width/a;e.setViewOffset(t.width,o,s.x,s.y,t.width,o),e.userData.__jittered=!0}_clearJitter(e){e.userData.__jittered&&(e.clearViewOffset(),delete e.userData.__jittered)}},f.SSAAPlugin.PluginType="SSAAPlugin",Vd([z(),ae("Enabled"),de(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"enabled",2),Vd([z(),Oe("Renders/Frame",[1,32],1),de(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"rendersPerFrame",2),Vd([z(),ae("Render Camera"),de(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"jitterRenderCamera",2),Vd([z(),ae("Light Cameras"),de(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"jitterLightCameras",2),f.SSAAPlugin=Vd([gt("SSAA Plugin")],f.SSAAPlugin);var G5=Object.defineProperty,z5=Object.getOwnPropertyDescriptor,g_=(r,e,t,i)=>{for(var n=i>1?void 0:i?z5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&G5(e,t,n),n};f.ProgressivePlugin=class extends Tl{constructor(e=32,t=Wt,i=!0){super(),this.passId="progressive",this._targets=new Map,this.maxFrameCount=e,this.enabled=i,this.bufferType=t}get texture(){return this.target?.texture}get target(){return this._viewer?this._targets.get(this._viewer.scene.renderCamera.uuid):void 0}getTarget(e){return this._viewer?this._targets.get((e||this._viewer.scene.renderCamera).uuid):void 0}get textures(){return this._viewer?Array.from(this._targets.values()).map(e=>e.texture):[]}get mainTexture(){return this._viewer?this.getTarget(this._viewer.scene.mainCamera)?.texture:void 0}_createTarget(e,t=!1){if(!this._viewer)return;if(e=e??this._viewer.scene.renderCamera,t&&this._disposeTarget(e),this._targets.has(e.uuid))return this._targets.get(e.uuid);const i=this._viewer.renderManager.composerTarget.clone(!0);return i.texture.name="progressiveLastBuffer_"+e.uuid,this._targets.set(e.uuid,i),i}_disposeTarget(e){if(this._viewer)if(!e)this._targets.forEach(t=>this._viewer.renderManager.disposeTarget(t)),this._targets.clear();else{const t=this._targets.get(e.uuid);t&&(this._viewer.renderManager.disposeTarget(t),this._targets.delete(e.uuid))}}_createPass(){const e=new fI(this.passId,()=>this.target??this._createTarget(),this._viewer?.renderManager.maxHDRIntensity);return e.dirty=()=>(this._viewer?.renderManager.frameCount||0)<this.maxFrameCount,e}onAdded(e){super.onAdded(e)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}isConverged(e=!1){return(this._viewer?.renderManager.frameCount||0)>=this.maxFrameCount-1+(e?1:0)}updateShaderProperties(e){return e.uniforms.tLastFrame&&(e.uniforms.tLastFrame.value=this.target?.texture??void 0),this}postFrameConvergedRecordingDelta(e="CanvasRecorder"){return-1}get convergedPromise(){return new Promise(e=>{if(this.isConverged())this._viewer?.doOnce("postFrame",()=>e());else{const t=()=>{this.isConverged(!0)&&(this._viewer?.removeEventListener("postRender",t),this._viewer?.doOnce("postFrame",()=>e()))};this._viewer?.addEventListener("postRender",t)}})}fromJSON(e,t){if(e.jitter!==void 0){const i=this._viewer?.getPlugin(f.SSAAPlugin);i?(e={...e},i.enabled=e.jitter,delete e.jitter):console.warn("Loading old webgi v0 file, add SSAAPlugin to get anti-aliasing")}return super.fromJSON(e,t)}},f.ProgressivePlugin.PluginType="ProgressivePlugin",f.ProgressivePlugin.OldPluginType="Progressive",g_([z(),Fe("Frame count")],f.ProgressivePlugin.prototype,"maxFrameCount",2),g_([Dr("Last Texture",{readOnly:!0})],f.ProgressivePlugin.prototype,"mainTexture",1),f.ProgressivePlugin=g_([gt("Progressive Plugin")],f.ProgressivePlugin);class fI extends dI{constructor(e,t,i=120){super(void 0,i),this.passId=e,this.target=t,this.before=["screen"],this.after=["render"],this.required=["render"],this.dirty=()=>!1,this.copyToWriteBuffer=!0}render(e,t,i,n,s){if(!this.enabled)return;const a=it(this.target);if(!a){console.warn("ProgressiveBlendPass: target not defined");return}if(this.needsSwap=!1,e.renderManager.frameCount<1){i?.texture&&e.renderManager.blit(a,{source:i.texture,respectColorSpace:!1});return}super.render(e,t,i,n,s),this.copyToWriteBuffer&&(e.renderManager.blit(a,{source:t.texture,respectColorSpace:!1}),this.needsSwap=!0)}beforeRender(e,t,i){if(!this.enabled)return;if(!this.target){console.error("ProgressiveBlendPass: render target undefined");return}let n=1/(Math.max(i.frameCount,0)+1);this.uniforms.weight.value.set(n,n,n,n),n=1-n,this.uniforms.weight2.value.set(n,n,n,n),this.uniforms.tDiffuse2.value=it(this.target)?.texture,this.material.uniformsNeedUpdate=!0}}const V5=`#if defined(HAS_DEPTH_BUFFER)
#if DEPTH_PACKING == 3200
#define unpackDepth(rgba_depth) (1.0 - rgba_depth.r)
#elif DEPTH_PACKING == 3201
#define unpackDepth(rgba_depth) unpackRGBAToDepth(rgba_depth)
#endif
uniform sampler2D tDepthBuffer;
#define getDepth(uv) unpackDepth(texture2D(tDepthBuffer, uv))
#endif
`;var H5=Object.defineProperty,Q5=Object.getOwnPropertyDescriptor,A_=(r,e,t,i)=>{for(var n=i>1?void 0:i?Q5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&H5(e,t,n),n};f.DepthBufferPlugin=class extends Tl{constructor(e=Wt,t=!1,i=!0,n=tc){super(),this.passId="depth",this.material=new pI({depthPacking:tc,blending:gn,transparent:!0}),this.unpackExtension={shaderExtender:s=>{const o=["depth_buffer_unpack","gbuffer_unpack","packing"].find(l=>s.fragmentShader.includes(`#include <${l}>`));s.fragmentShader=At(s.fragmentShader,`#include <${o}>`,`
`+V5+`
`,{append:o==="packing"})},extraUniforms:{tDepthBuffer:()=>({value:this.target?.texture})},extraDefines:{DEPTH_PACKING:tc,HAS_DEPTH_BUFFER:()=>this.target?.texture?1:void 0,HAS_GBUFFER:()=>this.isPrimaryGBuffer&&this.target?.texture?1:void 0},priority:100,isCompatible:()=>!0},this._isPrimaryGBufferSet=!1,this.enabled=i,this.depthPacking=n,this.bufferType=e,this.isPrimaryGBuffer=t}_depthPackingChanged(){this.material.depthPacking=this.depthPacking,this.material.needsUpdate=!0,this.unpackExtension&&this.unpackExtension.extraDefines&&(this.unpackExtension.extraDefines.DEPTH_PACKING=this.depthPacking,this.unpackExtension.setDirty?.()),this.setDirty()}_createTarget(e=!0){if(!this._viewer)return;e&&this._disposeTarget();const t=this._viewer.renderManager;this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:this._viewer.renderManager.zPrepass&&this.isPrimaryGBuffer&&t.msaa?typeof t.msaa!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:t.msaa:0,type:this.bufferType})),this.texture=this.target.texture,this.texture.name="depthBuffer",this.isPrimaryGBuffer&&(this._viewer.renderManager.gbufferTarget=this.target,this._viewer.renderManager.gbufferUnpackExtension=this.unpackExtension,this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension]),this._isPrimaryGBufferSet=!0)}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0,this._isPrimaryGBufferSet&&(this._viewer.renderManager.gbufferTarget=void 0,this._viewer.renderManager.gbufferUnpackExtension=void 0,this._isPrimaryGBufferSet=!1))}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("DepthBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=new f.GBufferRenderPass(this.passId,()=>this.target,this.material,new se(0,0,0),1),t=e.preprocessMaterial;return e.preprocessMaterial=i=>t(i,i.userData.renderToDepth),e.before=["render"],e.after=[],e.required=["render"],e}onRemove(e){return this._disposeTarget(),super.onRemove(e)}},f.DepthBufferPlugin.PluginType="DepthBufferPlugin",A_([Dr("Depth Buffer",{readOnly:!0})],f.DepthBufferPlugin.prototype,"texture",2),A_([de(f.DepthBufferPlugin.prototype._depthPackingChanged),Oi("Depth Packing",Mv.DepthPackingStrategies.uiConfig)],f.DepthBufferPlugin.prototype,"depthPacking",2),f.DepthBufferPlugin=A_([gt("Depth Buffer Plugin")],f.DepthBufferPlugin);class pI extends xc{constructor(e){super(e),this.reset()}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a);let o=s.material;Array.isArray(o)&&(o=o[0]),o&&(o.map!==void 0&&(this.map=o.map),o.side!==void 0&&(this.side=o.side??fs),o.alphaMap!==void 0&&(this.alphaMap=o.alphaMap),o.alphaTest!==void 0&&(this.alphaTest=o.alphaTest<1e-4?1e-4:o.alphaTest),o.alphaHash!==void 0&&(this.alphaHash=o.alphaHash),o.displacementMap!==void 0&&(this.displacementMap=o.displacementMap),o.displacementScale!==void 0&&(this.displacementScale=o.displacementScale),o.displacementBias!==void 0&&(this.displacementBias=o.displacementBias),o.wireframe!==void 0&&(this.wireframe=o.wireframe),o.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=o.wireframeLinewidth),this.needsUpdate=!0,e.resetCurrentMaterial&&e.resetCurrentMaterial())}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),this.reset()}reset(){this.map=null,this.side=Zi,this.alphaMap=null,this.alphaTest=.001,this.alphaHash=!1,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1}}var j5=Object.defineProperty,W5=Object.getOwnPropertyDescriptor,mI=(r,e,t,i)=>{for(var n=i>1?void 0:i?W5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&j5(e,t,n),n};f.NormalBufferPlugin=class extends Tl{constructor(e=$t,t=!0){super(),this.passId="normal",this.material=new gI({blending:gn}),this.enabled=t,this.bufferType=e}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:0,type:this.bufferType,magFilter:pi,minFilter:pi,generateMipmaps:!1,colorSpace:Dt})),this.texture=this.target.texture,this.texture.name="normalBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("NormalBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=new f.GBufferRenderPass(this.passId,()=>this.target,this.material,new se(0,0,0),1),t=e.preprocessMaterial;return e.preprocessMaterial=i=>t(i,!0),e.preprocessObject=i=>{if(i.customNormalMaterial){const n=i.customNormalMaterial;n.allowOverride=!1,i.forcedOverrideMaterial=n;return}return i.material},e.postprocessObject=i=>{i.customNormalMaterial&&delete i.forcedOverrideMaterial},e.before=["render"],e.after=[],e.required=["render"],e}onRemove(e){return this._disposeTarget(),super.onRemove(e)}},f.NormalBufferPlugin.PluginType="NormalBufferPlugin",mI([Dr("Normal Buffer",{readOnly:!0})],f.NormalBufferPlugin.prototype,"texture",2),f.NormalBufferPlugin=mI([gt("Normal Buffer Plugin")],f.NormalBufferPlugin);class gI extends wy{constructor(e){super(e),this.reset()}onBeforeRender(e,t,i,n,s,a){if(super.onBeforeRender(e,t,i,n,s,a),!s.material)return;const o=s.material;o.bumpMap!==void 0&&(this.bumpMap=o.bumpMap),o.bumpScale!==void 0&&(this.bumpScale=o.bumpScale),o.alphaTest!==void 0&&(this.alphaTest=o.alphaTest<1e-4?1e-4:o.alphaTest),o.alphaHash!==void 0&&(this.alphaHash=o.alphaHash),o.normalMap!==void 0&&(this.normalMap=o.normalMap),o.normalMapType!==void 0&&(this.normalMapType=o.normalMapType),o.normalScale!==void 0&&this.normalScale.copy(o.normalScale),o.displacementMap!==void 0&&(this.displacementMap=o.displacementMap),o.displacementScale!==void 0&&(this.displacementScale=o.displacementScale),o.displacementBias!==void 0&&(this.displacementBias=o.displacementBias),o.flatShading!==void 0&&(this.flatShading=o.flatShading),o.side!==void 0&&(this.side=o.side),o.wireframe!==void 0&&(this.wireframe=o.wireframe),o.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=o.wireframeLinewidth),e.resetCurrentMaterial&&e.resetCurrentMaterial()}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),this.reset()}reset(){this.bumpMap=null,this.bumpScale=1,this.alphaTest=0,this.normalMap=null,this.normalMapType=ks,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.flatShading=!1,this.side=Zi,this.wireframe=!1,this.wireframeLinewidth=1}}var q5=Object.defineProperty,X5=Object.getOwnPropertyDescriptor,Sg=(r,e,t,i)=>{for(var n=i>1?void 0:i?X5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&q5(e,t,n),n};f.FrameFadePlugin=class extends Tl{constructor(e=!0){super(),this.passId="frameFade",this.dependencies=[f.ProgressivePlugin],this.isEditor=!1,this.fadeOnActiveCameraChange=!0,this.fadeOnMaterialUpdate=!0,this.fadeOnSceneUpdate=!0,this._pointerEnabled=!0,this.saveFrameTimeThreshold=500,this._fadeCam=async t=>t.frameFade!==!1&&!this.isEditor&&this.fadeOnActiveCameraChange&&this.startTransition(t.fadeDuration||1e3),this._fadeMat=async t=>t.frameFade!==!1&&!this.isEditor&&this.fadeOnMaterialUpdate&&this.startTransition(t.fadeDuration||200),this._fadeScene=async t=>t.frameFade!==!1&&!this.isEditor&&this.fadeOnSceneUpdate&&this.startTransition(t.fadeDuration||500),this._fadeObjectUpdate=async t=>t.frameFade&&!this.isEditor&&this.startTransition(t.fadeDuration||500),this._onPointerMove=t=>{const i=this._viewer?.canvas;if(!i){this._pointerEnabled=!1;return}if(!t.buttons||t.target!==i){this._pointerEnabled=!0;return}const n=i.getBoundingClientRect(),s=(t.clientX-n.left)/n.width,a=(t.clientY-n.top)/n.height;this._pointerEnabled=s<0||s>1||a<0||a>1},this.enabled=e,this.startTransition=this.startTransition.bind(this),this.stopTransition=this.stopTransition.bind(this),this._fadeCam=this._fadeCam.bind(this),this._fadeMat=this._fadeMat.bind(this),this.isDisabled=(t=>()=>!this._pointerEnabled||t())(this.isDisabled)}async startTransition(e){!this._viewer||!this._pass||this.isDisabled()||(this._target||(this._target=this._viewer.renderManager.getTempTarget({sizeMultiplier:1,minFilter:st,magFilter:st,colorSpace:this._viewer.renderManager.composerTarget.texture.colorSpace})),this._pass.fadeTimeState<this.saveFrameTimeThreshold&&(this._pass.toSaveFrame=!0),this._pass.fadeTimeState=Math.max(e,this._pass.fadeTimeState),this._pass.fadeTime=this._pass.fadeTimeState,this.setDirty(),await jn(e))}stopTransition(){this._pass&&(this._pass.fadeTimeState=0)}onAdded(e){super.onAdded(e),e.scene.addEventListener("mainCameraUpdate",this.stopTransition),e.scene.addEventListener("mainCameraChange",this._fadeCam),e.scene.addEventListener("materialUpdate",this._fadeMat),e.scene.addEventListener("sceneUpdate",this._fadeScene),e.scene.addEventListener("objectUpdate",this._fadeObjectUpdate),window.addEventListener("pointermove",this._onPointerMove)}onRemove(e){e.scene.removeEventListener("mainCameraUpdate",this.stopTransition),e.scene.removeEventListener("mainCameraChange",this._fadeCam),e.scene.removeEventListener("materialUpdate",this._fadeMat),e.scene.removeEventListener("sceneUpdate",this._fadeScene),e.scene.removeEventListener("objectUpdate",this._fadeObjectUpdate),window.removeEventListener("pointermove",this._onPointerMove),super.onRemove(e)}setDirty(){super.setDirty(),!this.isDisabled()&&this._viewer?.setDirty()}get dirty(){return!this.isDisabled()&&!!this._pass&&this._pass.fadeTimeState>0}set dirty(e){console.error("FrameFadePlugin.dirty is readonly")}_createPass(){return new AI(this.passId,this,this._viewer?.renderManager.maxHDRIntensity)}get canFrameFade(){return this._target&&this._pointerEnabled&&this.dirty&&this._pass&&this._pass.fadeTimeState>.001&&this._viewer&&this._viewer.scene.renderCamera===this._viewer.scene.mainCamera}get lastFrame(){return this._viewer?.getPlugin(f.ProgressivePlugin)?.texture}get target(){return this._target}_beforeRender(){return!super._beforeRender()||!this._pass?!1:(this.isDisabled()&&this.stopTransition(),this._pass.fadeTimeState<.001&&(this._pass.toSaveFrame=!1,this._target&&this._viewer&&(this._viewer.renderManager.releaseTempTarget(this._target),this._target=void 0)),!0)}},f.FrameFadePlugin.PluginType="FrameFadePlugin",Sg([z(),ae()],f.FrameFadePlugin.prototype,"fadeOnActiveCameraChange",2),Sg([z(),ae()],f.FrameFadePlugin.prototype,"fadeOnMaterialUpdate",2),Sg([z(),ae()],f.FrameFadePlugin.prototype,"fadeOnSceneUpdate",2),f.FrameFadePlugin=Sg([gt("FrameFade Plugin")],f.FrameFadePlugin);class AI extends dI{constructor(e,t,i=120){super(void 0,i),this.passId=e,this.plugin=t,this.before=["progressive","taa"],this.after=["render"],this.required=["render","progressive"],this.dirty=()=>!1,this.fadeTime=0,this.fadeTimeState=0,this.toSaveFrame=!1,this._lastTime=0}render(e,t,i,n,s){this.needsSwap=!1;const a=this.plugin.target;if(!this.plugin.canFrameFade||!a)return;const o=this.plugin.lastFrame;this.toSaveFrame&&o&&(e.renderManager.blit(a,{source:o,respectColorSpace:!1}),this._lastTime=0,this.toSaveFrame=!1),this.uniforms.tDiffuse2.value=a.texture;const l=this.fadeTimeState/this.fadeTime;this.uniforms.weight2.value.setScalar(l),this.uniforms.weight2.value.w=1,this.uniforms.weight.value.setScalar(1-l),this.uniforms.weight.value.w=1,super.render(e,t,i,n,s),this.needsSwap=!0;const c=Mn();this._lastTime<10&&(this._lastTime=c-10);const h=c-this._lastTime;this._lastTime=c,this.fadeTimeState-=h}}const Y5=`#include <randomHelpers>
#include <common>
#include <packing>
#define THREE_PACKING_INCLUDED
#include <cameraHelpers>
varying vec2 vUv;uniform sampler2D tLastThis;
#ifndef D_frameCount
#define D_frameCount
uniform float frameCount;
#endif
uniform vec4 saoData;uniform vec4 saoBiasEpsilon;uniform vec2 screenSize;const float INV_NUM_SAMPLES=1.0/float(NUM_SAMPLES);int getSelectionBit(in int number){
#ifdef WebGL2Context
return(number/8)% 2;
#else
return int(mod(floor(float(number)/8.),2.));
#endif
}vec3 packFloatToRGB(const in float x){const vec3 code=vec3(1.0,255.0,65025.0);vec3 pack=vec3(code*x);pack.gb=fract(pack.gb);pack.rg-=pack.gb*(1.0/256.0);return pack;}vec3 getPositionFromOffset(const in vec2 uvOffset){
#if defined(HAS_DEPTH_BUFFER) || defined(HAS_NORMAL_DEPTH_BUFFER)
float d=getDepth(uvOffset);
#else
float d=0.5;
#endif
#if LINEAR_DEPTH == 0
float centerViewZ=viewZFromNDCZ(d);return screenToView3(uvOffset,centerViewZ);
#else
d=mix(-cameraNearFar.x,-cameraNearFar.y,d);return screenToView3(uvOffset,d);
#endif
}float getOcclusion(const in vec2 uv,const in int id,const in float randomAngle,const in float occlusionSphereRadius,const in vec3 centerPosition,const in vec3 centerNormal){float screenSpaceRadius=(float(id)+mod(randomAngle,1.)+0.5)*INV_NUM_SAMPLES;float angle=screenSpaceRadius*(float(NUM_SPIRAL_TURNS)*6.28318)+randomAngle;screenSpaceRadius=(screenSpaceRadius*occlusionSphereRadius);vec2 uvOffset=uv+floor(screenSpaceRadius*vec2(cos(angle),sin(angle)))/screenSize;
#if CHECK_GBUFFER_FLAG == 1
if(getSelectionBit(getGBufferFlags(uvOffset.xy).a)<1)return 0.0;
#endif
vec3 samplePosition=getPositionFromOffset(uvOffset);vec3 direction=samplePosition-centerPosition;float d2=dot(direction,direction)/(saoBiasEpsilon.w*saoBiasEpsilon.w);float ao=max((dot(centerNormal,direction)/saoBiasEpsilon.w-saoBiasEpsilon.x)/(saoBiasEpsilon.z*d2+saoBiasEpsilon.y),0.0);return ao;}void main(){float centerDepth=0.5;vec3 centerNormal=vec3(0,1,0);
#ifdef HAS_NORMAL_DEPTH_BUFFER
getDepthNormal(vUv,centerDepth,centerNormal);
#else
#ifdef HAS_DEPTH_BUFFER
centerDepth=getDepth(vUv);
#endif
#endif
#if LINEAR_DEPTH == 0
float centerViewZ=viewZFromNDCZ(centerDepth);
#else
float centerViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,centerDepth);
#endif
vec3 centerPosition=screenToView3(vUv,centerViewZ);float occlusionSphereScreenRadius=saoData.z*saoBiasEpsilon.w/(-centerPosition.z);float randomAngle=6.2*random3(vec3(vUv,frameCount*0.1));float sum=0.0;sum+=getOcclusion(vUv,0,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#if NUM_SAMPLES > 1
sum+=getOcclusion(vUv,1,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 2
sum+=getOcclusion(vUv,2,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 3
sum+=getOcclusion(vUv,3,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 4
sum+=getOcclusion(vUv,4,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 5
sum+=getOcclusion(vUv,5,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 6
sum+=getOcclusion(vUv,6,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 7
sum+=getOcclusion(vUv,7,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 8
sum+=getOcclusion(vUv,8,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 9
sum+=getOcclusion(vUv,9,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 10
sum+=getOcclusion(vUv,10,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
float aoValue=sum*saoData.y*INV_NUM_SAMPLES;aoValue=1.-clamp(aoValue,0.,1.);
#if SSAO_PACKING == 1
gl_FragColor.gba=packFloatToRGB(centerDepth);gl_FragColor.r=aoValue;
#elif SSAO_PACKING == 2
gl_FragColor.rgb=vec3(aoValue);gl_FragColor.a=1.;
#elif SSAO_PACKING == 3
gl_FragColor.rgba=packDepthToRGBA(aoValue);
#elif SSAO_PACKING == 4
gl_FragColor.rgb=packFloatToRGB(aoValue);gl_FragColor.a=1.;
#endif
}`,$5=`
#ifndef USE_TRANSMISSION
#if defined(SSAO_ENABLED) && SSAO_ENABLED > 0
vec3 screenPos_ao=viewToScreen(vViewPosition.xyz);
#if SSAO_ENABLED == 2
if(screenPos_ao.x>ssaoSplitX){
#endif
float ambientOcclusion=tSSAOMapTexelToLinear(texture2D(tSSAOMap,viewToScreen(vViewPosition.xyz).xy)).r;reflectedLight.indirectDiffuse*=ambientOcclusion;
#if defined( USE_ENVMAP )
float dotNV=saturate(dot(geometryNormal,geometryViewDir));reflectedLight.indirectSpecular*=computeSpecularOcclusion(dotNV,ambientOcclusion,material.roughness);
#endif
#else
#include <aomap_fragment>
#endif
#if SSAO_ENABLED == 2
}
#endif
#endif
`;var K5=Object.defineProperty,J5=Object.getOwnPropertyDescriptor,er=(r,e,t,i)=>{for(var n=i>1?void 0:i?J5(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&K5(e,t,n),n};f.SSAOPlugin=class extends Tl{constructor(e=Wt,t=1,i=!0,n=1){super(),this.passId="ssao",this.dependencies=[f.GBufferPlugin],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSAOPlugin: pass/viewer not created yet");const s=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==s&&(this._gbufferUnpackExtension&&this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=s,this._gbufferUnpackExtension?this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]):this._viewer.console.warn("SSAOPlugin: GBuffer unpack extension removed"))},this.enabled=i,this.bufferType=e,this.sizeMultiplier=t,this.packing=n}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier,colorSpace:Dt})),this.texture=this.target.texture,this.texture.name="ssaoBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSAOPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSAOPlugin: GBuffer target not created. GBufferPlugin or DepthBufferPlugin is required.");return this._createTarget(!0),new f.SSAOPluginPass(this.passId,()=>this.target,this.packing)}onAdded(e){super.onAdded(e),e.forPlugin(f.GBufferPlugin,t=>{t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this))},t=>{t.unregisterGBufferUpdater(this.constructor.PluginType)},this),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}fromJSON(e,t){return e.passes?.ssao&&(e={...e},e.pass=e.passes.ssao,delete e.passes,e.pass.enabled!==void 0&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}updateGBufferFlags(e,t){if(!t.material||!t.material.userData)return;const i=t.material.userData.ssaoCastDisabled||t.material.userData.pluginsDisabled,n=i?0:1;e.w=Jy(e.w,3,n),i&&this._pass&&(this._pass.checkGBufferFlag=!0)}get aoTarget(){return console.warn("SSAOPlugin: aoTarget is deprecated, use target instead"),this.target}},f.SSAOPlugin.PluginType="SSAOPlugin",f.SSAOPlugin.OldPluginType="SSAO",er([Dr("SSAO Buffer",{readOnly:!0,tags:["debug"]})],f.SSAOPlugin.prototype,"texture",2),er([Li(void 0,{unwrapContents:!0})],f.SSAOPlugin.prototype,"_pass",2),f.SSAOPlugin=er([gt("SSAO Plugin")],f.SSAOPlugin),f.SSAOPluginPass=class extends nh{constructor(e,t,i=1){super({defines:{LINEAR_DEPTH:1,NUM_SAMPLES:11,NUM_SPIRAL_TURNS:3,SSAO_PACKING:i,PERSPECTIVE_CAMERA:1,CHECK_GBUFFER_FLAG:0},uniforms:{screenSize:{value:new $(0,0)},saoData:{value:new rt},frameCount:{value:0},cameraNearFar:{value:new $(.1,1e3)},projection:{value:new pe},saoBiasEpsilon:{value:new rt(1,1,1,1)},sceneBoundingRadius:{value:0},ssaoSplitX:{value:.5}},vertexShader:sv.defaultVertex,fragmentShader:Y5},"tDiffuse"),this.passId=e,this.target=t,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render"],this.intensity=.25,this.occlusionWorldRadius=1,this.autoRadius=!1,this.bias=.001,this.falloff=1.3,this.numSamples=8,this.checkGBufferFlag=!1,this.split=0,this.copyToWriteBuffer=!1,this._projScale=1,this.materialExtension={extraUniforms:{tSSAOMap:()=>({value:it(this.target)?.texture??null}),ssaoSplitX:this.material.uniforms.ssaoSplitX},shaderExtender:(n,s,a)=>{n.defines?.SSAO_ENABLED&&(n.fragmentShader=At(n.fragmentShader,"#include <aomap_fragment>",$5))},onObjectRender:(n,s,a)=>{const o=this.enabled&&a.userData.screenSpaceRendering!==!1&&!s.userData?.pluginsDisabled&&!s.userData?.ssaoDisabled?this.split>0?2:1:0;s.defines.SSAO_ENABLED!==o&&(s.defines.SSAO_ENABLED=o,s.needsUpdate=!0)},parsFragmentSnippet:()=>ma`
             uniform sampler2D tSSAOMap;
            #if defined(SSAO_ENABLED) && SSAO_ENABLED == 2
            uniform float ssaoSplitX;
            #endif
             ${bv("tSSAOMap",it(this.target)?.texture.colorSpace)}
             #include <simpleCameraHelpers>
        `,computeCacheKey:()=>(this.enabled?"1":"0")+it(this.target)?.texture?.colorSpace,uuid:f.SSAOPlugin.PluginType,..._M(this._getUiConfig.bind(this),f.SSAOPlugin.PluginType),isCompatible:n=>n.isPhysicalMaterial},this.needsSwap=!1,this.clear=!0}render(e,t,i,n,s){if(this.needsSwap=!1,!this.enabled)return;const a=it(this.target);if(!a){console.warn("SSAOPluginPass: target not defined");return}this._updateParameters(),super.render(e,a,i,n,s),this.copyToWriteBuffer&&(e.renderManager.blit(t,{source:a.texture,respectColorSpace:!0}),this.needsSwap=!0)}_updateParameters(){const e=this.material.uniforms.saoData.value;e.y=this.intensity,e.z=this.occlusionWorldRadius,e.z*=this._projScale*.25;const t=this.material.uniforms.saoBiasEpsilon.value;t.x=this.bias,t.y=.001,t.z=this.falloff,this.autoRadius?t.w=Math.min(this.material.uniforms.sceneBoundingRadius.value,100):t.w=1}beforeRender(e,t,i){if(!this.enabled)return;this.updateShaderProperties([t,i,e]);const n=Math.max(1,e.mainCamera.fov??1),s=i?.webglRenderer.domElement.height||1,a=1;this._projScale=s/(2*a*Math.tan(.5*n*Ut.DEG2RAD))}_getUiConfig(e){return{type:"folder",label:"SSAO",children:[{type:"checkbox",label:"Enabled",get value(){return!(e.userData.ssaoDisabled??!1)},set value(t){t!==!(e.userData.ssaoDisabled??!1)&&(e.userData.ssaoDisabled=!t,e.setDirty())},onChange:this.setDirty},{type:"checkbox",label:"Cast SSAO",get value(){return!(e.userData.ssaoCastDisabled??!1)},set value(t){t!==!(e.userData.ssaoCastDisabled??!1)&&(e.userData.ssaoCastDisabled=!t,e.setDirty())},onChange:this.setDirty}]}}},er([z(),Oe("Intensity",[0,4],1e-4),ei(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"intensity",2),er([z(),Oe("Occlusion World Radius",[.1,8],.01),ei(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"occlusionWorldRadius",2),er([z(),ei(f.SSAOPluginPass.prototype.setDirty),ae()],f.SSAOPluginPass.prototype,"autoRadius",2),er([z(),Oe("Bias",[1e-5,.01],1e-5),ei(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"bias",2),er([z(),Oe("Falloff",[.01,3],.01),ei(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"falloff",2),er([z(),Oe("Num Samples",[1,11],1,{tags:["performance"]}),hm("NUM_SAMPLES",void 0,void 0,f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"numSamples",2),er([um("CHECK_GBUFFER_FLAG")],f.SSAOPluginPass.prototype,"checkGBufferFlag",2),er([Oe("Split",[0,1],.01,{tags:["debug"]}),z(),va({propKey:"ssaoSplitX",onChange:f.SSAOPluginPass.prototype.setDirty})],f.SSAOPluginPass.prototype,"split",2),f.SSAOPluginPass=er([gt("SSAO Pass")],f.SSAOPluginPass);const Z5='#RenderTargetPreviewPluginContainer{position:absolute;left:0;bottom:0;width:100%;z-index:1000;display:flex;flex-wrap:wrap;flex-direction:row;gap:5px;padding:5px;pointer-events:none;height:auto}.RenderTargetPreviewPluginTarget{position:relative;width:200px;height:200px}.RenderTargetPreviewPluginCollapsed{height:25px}.RenderTargetPreviewPluginTargetHeader{position:absolute;top:0;left:0;right:0;background:#00000080;color:#fff;padding:2px;font-size:16px;height:20px;font-family:monospace;text-align:center;pointer-events:auto;cursor:pointer}.RenderTargetPreviewPluginTargetHeader:after{content:"-";position:absolute;right:2px;width:20px;height:20px;line-height:16px}.RenderTargetPreviewPluginCollapsed .RenderTargetPreviewPluginTargetHeader:after{content:"+";line-height:20px}';var ej=Object.defineProperty,tj=Object.getOwnPropertyDescriptor,yI=(r,e,t,i)=>{for(var n=i>1?void 0:i?tj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&ej(e,t,n),n};f.RenderTargetPreviewPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=Pr({id:"RenderTargetPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const t of this.targetBlocks){if(!t.visible)continue;const i=it(t.target);if(!i)continue;const n=t.div.getBoundingClientRect();let s=t.textureIndex!==void 0&&i.textures?.[t.textureIndex]?i.textures[t.textureIndex]:i.texture;const a=this._viewer.canvas.getBoundingClientRect();n.x=n.x-a.x,n.y=a.height+a.y-n.y-n.height,Array.isArray(s)&&(s=s[0]);const o=this._viewer.renderManager.webglRenderer.outputColorSpace;t.originalColorSpace||(this._viewer.renderManager.webglRenderer.outputColorSpace=vt),this._viewer.renderManager.blit(null,{source:s,clear:!t.transparent,respectColorSpace:!t.originalColorSpace,viewport:new rt(n.x,n.y,n.width,n.height),material:t.material}),this._viewer.renderManager.webglRenderer.outputColorSpace=o}},this.enabled=e}onAdded(e){super.onAdded(e),e.addEventListener("postRender",this._postRender),this.stylesheet=ll(Z5,e.container),this.refreshUi()}onRemove(e){e.removeEventListener("postRender",this._postRender),this.stylesheet?.remove(),this.stylesheet=void 0,this.refreshUi(),super.onRemove(e)}addTarget(e,t,i=!1,n=!1,s=!0,a,o){if(!e)return this;const l=document.createElement("div"),c={target:e,name:t,transparent:i,div:l,originalColorSpace:n,visible:s,textureIndex:o};a&&(c.material=a?.isMaterial?a:new y0(a).material),l.classList.add("RenderTargetPreviewPluginTarget"),c.visible||l.classList.add("RenderTargetPreviewPluginCollapsed");const h=document.createElement("div");return h.classList.add("RenderTargetPreviewPluginTargetHeader"),h.innerText=t,h.onclick=()=>{c.visible=!c.visible,c.visible?l.classList.remove("RenderTargetPreviewPluginCollapsed"):l.classList.add("RenderTargetPreviewPluginCollapsed"),this._viewer?.setDirty()},h.oncontextmenu=u=>{u.preventDefault(),u.stopPropagation(),Wu.Create({Download:()=>this.downloadTarget(e,o),Remove:()=>this.removeTarget(e)},u.clientX,u.clientY)},l.appendChild(h),this.mainDiv.appendChild(l),this.targetBlocks.push(c),this.refreshUi(),this}removeTarget(e){const t=this.targetBlocks.findIndex(i=>i.target===e);if(t>=0){const i=this.targetBlocks[t];this.targetBlocks.splice(t,1),i.div.remove()}return this.refreshUi(),this}downloadTarget(e,t){if(!this._viewer)return this;const i=it(e);if(!i)return this;const n=this._viewer.renderManager.exportRenderTarget(i,"auto",t??0);return this._viewer.exportBlob(n,"renderTarget."+(n.ext||"png")),this}refreshUi(){if(this.mainDiv){if(!this._viewer){this.mainDiv.parentElement&&this.mainDiv.remove(),this.mainDiv.style.display="none",this.mainDiv.style.zIndex="1000";return}this.mainDiv.parentElement||this._viewer.container?.appendChild(this.mainDiv),this.mainDiv.style.display=this.isDisabled()?"none":"flex",this.mainDiv.style.zIndex=parseInt(this._viewer.canvas.style.zIndex||"0")+1+"",this._viewer?.setDirty()}}setDirty(){this.refreshUi()}dispose(){for(const e of this.targetBlocks)this.removeTarget(e.target);super.dispose()}},f.RenderTargetPreviewPlugin.PluginType="RenderTargetPreviewPlugin",yI([ae("Enabled"),de(f.RenderTargetPreviewPlugin.prototype.refreshUi)],f.RenderTargetPreviewPlugin.prototype,"enabled",2),f.RenderTargetPreviewPlugin=yI([gt("Render Target Preview Plugin")],f.RenderTargetPreviewPlugin);const ij='#GeometryUVPreviewPluginContainer{position:absolute;left:0;bottom:0;width:100%;z-index:1000;display:flex;flex-wrap:wrap;flex-direction:row;gap:5px;padding:5px;pointer-events:none;height:auto}.GeometryUVPreviewPluginTarget{position:relative;width:200px;height:200px}.GeometryUVPreviewPluginCollapsed{height:25px}.GeometryUVPreviewPluginTargetHeader{position:absolute;top:0;left:0;right:0;background:#00000080;color:#fff;padding:2px;font-size:16px;height:20px;font-family:monospace;text-align:center;pointer-events:auto;cursor:pointer}.GeometryUVPreviewPluginTargetHeader:after{content:"-";position:absolute;right:2px;width:20px;height:20px;line-height:16px}.GeometryUVPreviewPluginCollapsed .GeometryUVPreviewPluginTargetHeader:after{content:"+";line-height:20px}';var nj=Object.defineProperty,sj=Object.getOwnPropertyDescriptor,vI=(r,e,t,i)=>{for(var n=i>1?void 0:i?sj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&nj(e,t,n),n};f.GeometryUVPreviewPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=Pr({id:"GeometryUVPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const t of this.targetBlocks){if(!t.visible)continue;const i=it(t.target);i?.attributes?.uv&&(t.uvCanvas||(t.uvCanvas=O1(i,1024),t.uvCanvas.style.width="100%",t.uvCanvas.style.height="100%"),t.uvCanvas&&t.uvCanvas.parentElement!==t.div&&t.div.appendChild(t.uvCanvas))}},this.enabled=e}onAdded(e){super.onAdded(e),e.addEventListener("postRender",this._postRender),this.stylesheet=ll(ij,e.container),this.refreshUi()}onRemove(e){e.removeEventListener("postRender",this._postRender),this.stylesheet?.remove(),this.stylesheet=void 0,this.refreshUi(),super.onRemove(e)}addGeometry(e,t,i=!0){if(!e)return this;const n=document.createElement("div"),s={target:e,name:t,div:n,visible:i};n.classList.add("GeometryUVPreviewPluginTarget"),s.visible||n.classList.add("GeometryUVPreviewPluginCollapsed");const a=document.createElement("div");return a.classList.add("GeometryUVPreviewPluginTargetHeader"),a.innerText=t,a.onclick=()=>{s.visible=!s.visible,s.visible?n.classList.remove("GeometryUVPreviewPluginCollapsed"):n.classList.add("GeometryUVPreviewPluginCollapsed"),this._viewer?.setDirty()},a.oncontextmenu=o=>{o.preventDefault(),o.stopPropagation(),Wu.Create({Download:()=>this.downloadGeometryUV(s),Remove:()=>this.removeGeometry(e)},o.clientX,o.clientY)},n.appendChild(a),this.mainDiv.appendChild(n),this.targetBlocks.push(s),this.refreshUi(),this}removeGeometry(e){const t=this.targetBlocks.findIndex(i=>i.target===e);if(t>=0){const i=this.targetBlocks[t];this.targetBlocks.splice(t,1),i.div.remove()}return this.refreshUi(),this}downloadGeometryUV(e){if(!this._viewer)return this;if(!e.uvCanvas)return this;const i=e.uvCanvas.toDataURL("image/png"),n=document.createElement("a");return document.body.appendChild(n),n.style.display="none",n.href=i,n.download="renderTarget.png",n.click(),document.body.removeChild(n),URL.revokeObjectURL(i),this}refreshUi(){if(this.mainDiv){if(!this._viewer){this.mainDiv.parentElement&&this.mainDiv.remove(),this.mainDiv.style.display="none",this.mainDiv.style.zIndex="1000";return}this.mainDiv.parentElement||this._viewer.container?.appendChild(this.mainDiv),this.mainDiv.style.display=this.isDisabled()?"none":"flex",this.mainDiv.style.zIndex=parseInt(this._viewer.canvas.style.zIndex||"0")+1+"",this._viewer?.setDirty()}}setDirty(){this.refreshUi()}dispose(){for(const e of this.targetBlocks)this.removeGeometry(e.target);super.dispose()}},f.GeometryUVPreviewPlugin.PluginType="GeometryUVPreviewPlugin",vI([ae("Enabled"),de(f.GeometryUVPreviewPlugin.prototype.refreshUi)],f.GeometryUVPreviewPlugin.prototype,"enabled",2),f.GeometryUVPreviewPlugin=vI([gt("Render Target Preview Plugin")],f.GeometryUVPreviewPlugin);var rj=Object.defineProperty,aj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&rj(e,t,n),n};const tb=class tb extends pt{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.uiConfig,this.uiConfig.expanded=!0}};tb.PluginType="ViewerUiConfigPlugin";let Eg=tb;aj([z("viewer")],Eg.prototype,"_viewer");var oj=Object.defineProperty,lj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&oj(e,t,n),n};const ib=class ib extends pt{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.scene.uiConfig,this._scene=e.scene}};ib.PluginType="SceneUiConfigPlugin";let Mg=ib;lj([z("scene")],Mg.prototype,"_scene");var cj=Object.defineProperty,hj=Object.getOwnPropertyDescriptor,Tg=(r,e,t,i)=>{for(var n=i>1?void 0:i?hj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&cj(e,t,n),n};f.FullScreenPlugin=class extends pt{constructor(){super(),this.toJSON=void 0,this.enabled=!0,this._lastSize=["100%","100%"],this._lastFsElement=null,this._fsChangeHandler=e=>{if(this.isFullScreen())this.dispatchEvent({type:"enter"});else{const t=this._lastFsElement||this._viewer?.canvas;t&&(t.style.width=this._lastSize[0],t.style.height=this._lastSize[1]),document.removeEventListener("webkitfullscreenchange",this._fsChangeHandler,!1),document.removeEventListener("mozfullscreenchange",this._fsChangeHandler,!1),document.removeEventListener("fullscreenchange",this._fsChangeHandler,!1),document.removeEventListener("MSFullscreenChange",this._fsChangeHandler,!1),this.dispatchEvent({type:"exit"})}},this.enter=this.enter.bind(this),this.exit=this.exit.bind(this)}async enter(e){if(this.isFullScreen())return;const t=e||this._viewer?.canvas;if(t){if(this._lastFsElement=t,document.addEventListener&&(document.addEventListener("webkitfullscreenchange",this._fsChangeHandler,!1),document.addEventListener("mozfullscreenchange",this._fsChangeHandler,!1),document.addEventListener("fullscreenchange",this._fsChangeHandler,!1),document.addEventListener("MSFullscreenChange",this._fsChangeHandler,!1)),this._lastSize=[t.style.width,t.style.height],t.style.width="100%",t.style.height="100%",t.requestFullscreen)return t.requestFullscreen();if(t.mozRequestFullScreen)return t.mozRequestFullScreen();if(t.webkitRequestFullscreen)return t.webkitRequestFullscreen();if(t.msRequestFullscreen)return t.msRequestFullscreen()}}async exit(){if(document.exitFullscreen)return document.exitFullscreen();if(document.mozCancelFullScreen)return document.mozCancelFullScreen();if(document.webkitExitFullscreen)return document.webkitExitFullscreen();if(document.msExitFullscreen)return document.msExitFullscreen()}async toggle(e){return this.isFullScreen()?this.exit():this.enter(e)}isFullScreen(){return document.webkitIsFullScreen||document.mozFullScreen||document.msFullscreenElement!==void 0}},f.FullScreenPlugin.PluginType="FullScreenPlugin",Tg([lt("Enter FullScreen",{sendArgs:!1})],f.FullScreenPlugin.prototype,"enter",1),Tg([lt("Exit FullScreen",{sendArgs:!1})],f.FullScreenPlugin.prototype,"exit",1),Tg([lt("Toggle FullScreen",{sendArgs:!1})],f.FullScreenPlugin.prototype,"toggle",1),f.FullScreenPlugin=Tg([gt("Full Screen")],f.FullScreenPlugin);const uj='#assetManagerLoadingScreen{z-index:50;position:absolute;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";bottom:0;right:0;min-width:100%;min-height:100%;color:#333;font-size:1rem;gap:1rem;display:flex;align-content:center;justify-content:center;align-items:center;flex-direction:column;opacity:1;transition:opacity .5s ease-in-out,min-width .5s,min-height .5s,bottom .5s,right .5s;overflow:hidden;background:transparent;background-blend-mode:luminosity;--b-opacity: .8;--b-background: #fff;--b-blur: 24px;-webkit-backdrop-filter:blur(var(--b-blur));backdrop-filter:blur(var(--b-blur));pointer-events:none}#assetManagerLoadingScreen:before{content:"";position:absolute;top:0;left:0;width:100%;height:100%;z-index:-1;opacity:var(--b-opacity);background:var(--b-background)}#assetManagerLoadingScreenContent{padding-top:.5rem}.loadingScreenProcessState{font-weight:700}#assetManagerLoadingScreen.minimizedLoadingScreen{top:unset;left:unset;bottom:2rem;right:2rem;min-width:0;min-height:0;max-width:80vw;max-height:80vh;width:max-content;height:max-content;padding:1.5rem;border-radius:.5rem}.loadingScreenFilesElement{min-height:4rem;padding:1rem}.loadingScreenLogoElement{margin-bottom:.5rem;max-width:80%}.loadingScreenLogoElement img{min-height:3rem;max-height:5rem;max-width:100%;object-fit:contain}.loadingScreenLogoImage{width:max-content;height:max-content}.minimizedLoadingScreen .loadingScreenLoadingElement{display:none}.minimizedLoadingScreen .loadingScreenFilesElement{min-height:0}.minimizedLoadingScreen .loadingScreenLogoElement{min-height:0;display:none}.minimizedLoadingScreen #assetManagerLoadingScreenContent{display:none}',dj=".loader{width:48px;height:48px;border:5px solid #333;border-bottom-color:transparent;border-radius:50%;display:inline-block;box-sizing:border-box;animation:rotation 1s linear infinite}@keyframes rotation{0%{transform:rotate(0)}to{transform:rotate(360deg)}}";var fj=Object.defineProperty,pj=Object.getOwnPropertyDescriptor,Yi=(r,e,t,i)=>{for(var n=i>1?void 0:i?pj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&fj(e,t,n),n};f.LoadingScreenPlugin=class extends uI{constructor(e){super("LoadingScreen",e),this.styles=uj,this.spinners=[{styles:dj,html:'<span class="loader"></span>'}],this.loader=0,this.loadingTextHeader="Loading Files",this.errorTextHeader="Error Loading Files",this.showFileNames=!0,this.showProcessStates=!0,this.showProgress=!0,this.hideOnOnlyErrors=!0,this.hideOnFilesLoad=!0,this.hideOnSceneObjectLoad=!1,this.minimizeOnSceneObjectLoad=!0,this.showOnFilesLoading=!0,this.showOnSceneEmpty=!0,this.hideDelay=500,this.backgroundOpacity=.5,this.backgroundBlur=24,this.background="#ffffff",this.textColor="#222222",this.logoImage=f.LoadingScreenPlugin.LS_DEFAULT_LOGO,this._isPreviewing=!1,this._previewState=new Map([["file.glb",{state:"downloading",progress:50}],["environment.hdr",{state:"adding"}]]),this.loadingElement=Pr({classList:["loadingScreenLoadingElement"],addToBody:!1}),this.filesElement=Pr({classList:["loadingScreenFilesElement"],addToBody:!1}),this.logoElement=Pr({classList:["loadingScreenLogoElement"],addToBody:!1}),this._isHidden=!1,this._temp=document.createElement("template"),this.isEditor=!1,this._sceneUpdate=t=>{if(!this._viewer||!t.hierarchyChanged)return;const i=this._viewer.scene.modelRoot.children;if(i.length===0&&this.showOnSceneEmpty&&!this.isEditor&&this.show(),i.length>0){const n=this._viewer.assetManager.processState,s=[...n.values()].filter(a=>a.state==="error");this._updateVisibility(n,s.length)||(this.hideOnSceneObjectLoad?this.hideWithDelay():this.minimizeOnSceneObjectLoad&&this._viewer.scene.environment&&jn(this.hideDelay+300).then(()=>this.minimize()))}else this.minimizeOnSceneObjectLoad&&this.maximize()},this._mainDiv.prepend(this.loadingElement),this._mainDiv.prepend(this.logoElement),this._mainDiv.appendChild(this.filesElement)}refresh(){this._viewer&&this._updateMainDiv(this._isPreviewing?this._previewState:this._viewer.assetManager.processState,!1)}togglePreview(){this.maximize(),this._isPreviewing=!this._isPreviewing,this.refresh(),this._isPreviewing?this.show():this.hideWithDelay()}get visible(){return!this._isHidden}async hide(){this._isHidden=!0,this._mainDiv.style.opacity="0",await jn(502),this._isHidden&&(this._mainDiv.style.display="none",this._showMainDiv())}async hideWithDelay(){if(this._isHidden=!0,await jn(this.hideDelay),!!this._isHidden)return this.hide()}show(){this._isHidden&&(this._isHidden=!1,this._showMainDiv(),this._mainDiv.style.display="flex")}_showMainDiv(){this._mainDiv.style.opacity="1"}minimize(){this._mainDiv.classList.add("minimizedLoadingScreen"),this.showFileNames||(this.loadingElement.style.display="block")}maximize(){this._mainDiv.classList.remove("minimizedLoadingScreen"),this.loadingElement.style.display=""}_setHTML(e,t){this._temp.innerHTML=t,this._temp.innerHTML.trim()!==e.innerHTML.trim()&&(e.innerHTML=t)}_updateMainDiv(e,t=!0){if(!this._viewer||!this._contentDiv)return;if(!this.enabled){this._mainDiv.style.display="none";return}if(this.showFileNames){let n="";e.forEach((s,a)=>{n+=(this.showProcessStates?`<span class="loadingScreenProcessState">${Vs(s.state)}</span>: `:"")+Vs((a||"").split("/").pop()||"")+(this.showProgress&&s.progress?" - "+(s.progress.toFixed(0)+"%"):"")+"<br>"}),this._setHTML(this.filesElement,n)}else this._setHTML(this.filesElement,"");const i=[...e.values()].filter(n=>n.state==="error");i.length>0&&i.length===e.size&&!this.hideOnOnlyErrors?this._setHTML(this._contentDiv,Vs(this.errorTextHeader)):this._setHTML(this._contentDiv,Vs(this.loadingTextHeader)),this._setHTML(this.loadingElement,this.spinners[this.loader].html),this._mainDiv.style.setProperty("--b-opacity",this.backgroundOpacity.toString()),this._mainDiv.style.setProperty("--b-background",this.background),this._mainDiv.style.setProperty("--b-blur",this.backgroundBlur+"px"),this._mainDiv.style.color=this.textColor,this._setHTML(this.logoElement,this.logoImage?`<img class="loadingScreenLogoImage" src=${JSON.stringify(this.logoImage)}/>`:""),t&&this._updateVisibility(e,i.length)}_updateVisibility(e,t){return this._viewer?this.hideOnFilesLoad&&(e.size===0||t===e.size&&this.hideOnOnlyErrors)&&!this._isHidden?(this.hideDelay?this.hideWithDelay():this.hide(),!0):e.size>0&&this.showOnFilesLoading&&this._isHidden?(this._viewer.scene.modelRoot.children.length>0&&this.minimizeOnSceneObjectLoad&&this._viewer.scene.environment?this.minimize():this.maximize(),this.show(),!0):!1:!1}onAdded(e){this.stylesheet=ll(this.styles,e.container),this.stylesheetLoader=this.spinners.map(t=>ll(t.styles,e.container)),e.scene.addEventListener("sceneUpdate",this._sceneUpdate),super.onAdded(e)}onRemove(e){return e.scene.removeEventListener("sceneUpdate",this._sceneUpdate),this.stylesheet?.remove(),this.stylesheet=void 0,this.stylesheetLoader?.forEach(t=>t.remove()),this.stylesheetLoader=void 0,super.onRemove(e)}},f.LoadingScreenPlugin.PluginType="LoadingScreenPlugin",f.LoadingScreenPlugin.LS_DEFAULT_LOGO="https://threepipe.org/logo.svg",Yi([Oi("Loader",["Spinner 1"].map((r,e)=>({value:e,label:r}))),z()],f.LoadingScreenPlugin.prototype,"loader",2),Yi([Fe("Loading text header"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"loadingTextHeader",2),Yi([Fe("Error text header"),z()],f.LoadingScreenPlugin.prototype,"errorTextHeader",2),Yi([ae("Show file names"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"showFileNames",2),Yi([ae("Show process states"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"showProcessStates",2),Yi([ae("Show progress"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"showProgress",2),Yi([ae("Hide on only errors"),z()],f.LoadingScreenPlugin.prototype,"hideOnOnlyErrors",2),Yi([ae("Hide on files load"),z()],f.LoadingScreenPlugin.prototype,"hideOnFilesLoad",2),Yi([ae("Hide on scene object load"),z()],f.LoadingScreenPlugin.prototype,"hideOnSceneObjectLoad",2),Yi([ae("Minimize on scene object load"),z()],f.LoadingScreenPlugin.prototype,"minimizeOnSceneObjectLoad",2),Yi([ae("Show when files start loading"),z()],f.LoadingScreenPlugin.prototype,"showOnFilesLoading",2),Yi([ae("Show when scene empty"),z()],f.LoadingScreenPlugin.prototype,"showOnSceneEmpty",2),Yi([Fe("Hide delay (ms)"),z()],f.LoadingScreenPlugin.prototype,"hideDelay",2),Yi([Oe("Background Opacity",[0,1]),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"backgroundOpacity",2),Yi([Oe("Background Blur",[0,100]),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"backgroundBlur",2),Yi([Fe("Background Color"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"background",2),Yi([Fe("Text Color"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"textColor",2),Yi([Fe("Logo Image"),de(f.LoadingScreenPlugin.prototype.refresh),z()],f.LoadingScreenPlugin.prototype,"logoImage",2),Yi([lt("Toggle preview")],f.LoadingScreenPlugin.prototype,"togglePreview",1),Yi([lt("Minimize")],f.LoadingScreenPlugin.prototype,"minimize",1),Yi([lt("Maximize")],f.LoadingScreenPlugin.prototype,"maximize",1),f.LoadingScreenPlugin=Yi([gt("Loading Screen")],f.LoadingScreenPlugin);class _I extends Al{constructor(){super(),this.isWidget=!0,this.assetType="widget",this._object=null,this.boundingScaleMultiplier=1,this.position.set(0,0,0),this.visible=!1,this.renderOrder=100,this.userData.bboxVisible=!1,this._updater=this._updater.bind(this),this.detach=this.detach.bind(this),this.addEventListener("dispose",this.detach)}_updater(){const e=this._object;if(e){const t=new In().expandByObject(e,!1);t.getCenter(this.position);let i=t.getBoundingSphere(new un).radius;i<=0&&(e.getWorldPosition(this.position),i=.1),this.scale.setScalar(i*this.boundingScaleMultiplier).clampScalar(.01,1e8),this.setVisible(!0)}else this.setVisible(!1)}setVisible(e){e!==this.visible&&(this.visible=e,this.setDirty?.({sceneUpdate:!1}))}attach(e){this.detach();let t=!1;return e.traverseAncestors(i=>i.isRootScene&&(t=!0)),t?e?(this._object=e,this._object.addEventListener("objectUpdate",this._updater),this._object.addEventListener("geometryUpdate",this._updater),this._updater(),this):this:this}detach(){return this._object?(this._object?.removeEventListener("objectUpdate",this._updater),this._object?.removeEventListener("geometryUpdate",this._updater),this._object=null,this._updater(),this):this}get object(){return this._object}}var mj=Object.defineProperty,gj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&mj(e,t,n),n};const y_=class extends Al{constructor(e,t=!0){super(),this.isWidget=!0,this.assetType="widget",this.visible=!0,this._objectUpdated=!1,this.uiConfig=$p("Widget",this,{tags:"widget"}),this.object=e,this.object.updateMatrixWorld(),this.object.updateProjectionMatrix&&this.object.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.detach=this.detach.bind(this),this._objectUpdate=this._objectUpdate.bind(this),this._objectBeforeRender=this._objectBeforeRender.bind(this),t&&this.attach(e),this.traverse(i=>{i.userData.__keepShadowDef=!0,i.castShadow=!1,i.receiveShadow=!1}),this.renderOrder=100}update(e=!0){e&&Ge.setDirty.call(this)}_objectUpdate(){this._objectUpdated=!0}_objectBeforeRender(){this.visible&&this._objectUpdated&&(this._objectUpdated=!1,this.object&&this.update())}attach(e){return this.object&&this.detach(),this.object=e,this.object&&(this.update(),this.object.addEventListener("beforeRender",this._objectBeforeRender),this.object.addEventListener("objectUpdate",this._objectUpdate),this.object.addEventListener("geometryUpdate",this._objectUpdate),this.uiConfig&&this.object.uiConfig?.children?.push(this.uiConfig),this.visible=!0),this}detach(){if(!this.object)return this;if(this.object.removeEventListener("beforeRender",this._objectBeforeRender),this.object.removeEventListener("objectUpdate",this._objectUpdate),this.object.removeEventListener("geometryUpdate",this._objectUpdate),this.uiConfig){const e=this.object.uiConfig?.children?.indexOf(this.uiConfig);e!==void 0&&e>=0&&this.object.uiConfig?.children?.splice(e,1)}return this.object=void 0,this.visible=!1,this}dispose(){this.detach()}};gj([ae(),ei(y_.prototype.update)],y_.prototype,"visible");let Ch=y_;class bI extends Ch{constructor(e){super(e),this.camera=e,this.traverse(t=>{t.userData.__keepShadowDef=!0,t.castShadow=!1,t.receiveShadow=!1})}preRender(){this.visible&&this._objectBeforeRender()}attach(e){return super.attach(e),this}detach(){return super.detach()}}class Ig extends Ch{constructor(e){super(e),this.light=e,this.traverse(t=>{t.userData.__keepShadowDef=!0,t.castShadow=!1,t.receiveShadow=!1})}preRender(){this.visible&&this._objectBeforeRender()}}var Aj=Object.defineProperty,Hd=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Aj(e,t,n),n};const fr=class uP extends Ch{constructor(e,t,i){super(e),this._vector=new x,this._boneMatrix=new pe,this._matrixWorldInv=new pe,this.lineWidth=5,this.color1=new se(0,0,1),this.color2=new se(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i);const n=new Hs;this.hMaterial=new ji({vertexColors:!0,linewidth:this.lineWidth,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lineSegments=new _a(n,this.hMaterial),this.lineSegments.frustumCulled=!1,this.add(this.lineSegments),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.update()}updateMatrixWorld(e){this.object&&this.autoUpdate&&this.update(!1),super.updateMatrixWorld(e)}update(e=!0){if(!this.lineSegments||!this.object)return;const t=this.object;this.hMaterial.linewidth=this.lineWidth;const i=[],n=[];this._matrixWorldInv.copy(t.matrixWorld).invert(),t.parent&&t.parent.isBone&&(this._boneMatrix.multiplyMatrices(this._matrixWorldInv,t.parent.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i.push(this._vector.x,this._vector.y,this._vector.z),n.push(this.color1.r,this.color1.g,this.color1.b),this._boneMatrix.multiplyMatrices(this._matrixWorldInv,t.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i.push(this._vector.x,this._vector.y,this._vector.z),n.push(this.color2.r,this.color2.g,this.color2.b));const s=this.lineSegments.geometry;i.length>0?(s.setPositions(i),s.setColors(n)):(s.setPositions([0,0,0,0,0,0]),s.setColors([0,0,0,0,0,0])),super.update(e)}dispose(){this.lineSegments.geometry.dispose(),this.lineSegments.material.dispose(),super.dispose()}static Check(e){return e.isBone}static Create(e){return new uP(e)}};Hd([ei(fr.prototype.update)],fr.prototype,"hMaterial"),Hd([ei(fr.prototype.update),Oe(void 0,[.1,20],.01)],fr.prototype,"lineWidth"),Hd([ei(fr.prototype.update),Tn()],fr.prototype,"color1"),Hd([ei(fr.prototype.update),Tn()],fr.prototype,"color2"),Hd([ae(),ei(fr.prototype.update)],fr.prototype,"autoUpdate");let yj=fr;class wI extends _I{constructor(){super();const e=new ji({color:"#ff2222",transparent:!0,opacity:.9,linewidth:5,resolution:new $(1024,1024),worldUnits:!1,dashed:!1,toneMapped:!1,depthTest:!0,depthWrite:!1,allowOverride:!1});e.userData.renderToGBuffer=!1,e.userData.renderToDepth=!1,this.lineMaterial=e;const t=new Hs;t.setPositions([1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,1].map(n=>n-.5));const i=new _a(t,e);i.computeLineDistances(),i.scale.set(1,1,1),i.visible=!0,this.add(i)}_updater(){super._updater();const e=this.object;if(e){const i=new In().expandByObject(e,!1).getSize(this.scale);i.lengthSq()<=0&&(e.getWorldPosition(this.position),i.set(2,2,2)),i.multiplyScalar(this.boundingScaleMultiplier).clampScalar(.01,1e8),this.setVisible(!0)}}}var vj=Object.defineProperty,_j=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&vj(e,t,n),n};const v_=class dP extends bI{constructor(e){super(e),this._vector=new x,this._camera=new Ac,this._colorFrustum=new se(16755200),this._colorCone=new se(16711680),this._colorUp=new se(43775),this._colorTarget=new se(16777215),this._colorCross=new se(3355443),this.showFar=!1;const t=new Hs,i=new ji({color:16777215,linewidth:3,vertexColors:!0,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1});i.userData.renderToGBuffer=!1,i.userData.renderToDepth=!1;const{vertices:n,colors:s,pointMap:a}=bj();t.setPositions(n),t.setColors(s),this.line=new _a(t,i),this.line.frustumCulled=!1,this.add(this.line),this.pointMap=a,this.update(),this.setColors(this._colorFrustum,this._colorCone,this._colorUp,this._colorTarget,this._colorCross)}setColors(e,t,i,n,s){const a=this.line.geometry,o=a.getAttribute("instanceColorStart"),l=a.getAttribute("instanceColorEnd");let c=0;function h(u){o.setXYZ(c,u.r,u.g,u.b),l.setXYZ(c,u.r,u.g,u.b),c++}h(i),h(i),h(i),h(s),h(s),h(s),h(s),h(e),h(e),h(e),h(e),h(t),h(t),h(t),h(t),h(e),h(e),h(e),h(e),h(e),h(e),h(e),h(e),h(n),h(s),o.needsUpdate=!0,l.needsUpdate=!0}update(){if(!this.camera||!this.line)return;const e=this.line.geometry,t=this.pointMap,i=1,n=1,{_camera:s,_vector:a}=this;this.camera.updateProjectionMatrix(),s.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),cn("c",t,e,s,0,0,-1,a),cn("t",t,e,s,0,0,1,a),cn("n1",t,e,s,-i,-n,-1,a),cn("n2",t,e,s,i,-n,-1,a),cn("n3",t,e,s,-i,n,-1,a),cn("n4",t,e,s,i,n,-1,a),cn("f1",t,e,s,-i,-n,1,a),cn("f2",t,e,s,i,-n,1,a),cn("f3",t,e,s,-i,n,1,a),cn("f4",t,e,s,i,n,1,a),cn("u1",t,e,s,i*.7,n*1.1,-1,a),cn("u2",t,e,s,-i*.7,n*1.1,-1,a),cn("u3",t,e,s,0,n*2,-1,a),cn("cf1",t,e,s,-i,0,1,a),cn("cf2",t,e,s,i,0,1,a),cn("cf3",t,e,s,0,-n,1,a),cn("cf4",t,e,s,0,n,1,a),cn("cn1",t,e,s,-i,0,-1,a),cn("cn2",t,e,s,i,0,-1,a),cn("cn3",t,e,s,0,-n,-1,a),cn("cn4",t,e,s,0,n,-1,a),e.getAttribute("instanceStart").needsUpdate=!0,e.getAttribute("instanceEnd").needsUpdate=!0,e.computeBoundingBox(),e.computeBoundingSphere(),this.setColors(this._colorFrustum,this._colorCone,this._colorUp,this._colorTarget,this._colorCross),this.line.geometry.instanceCount=this.showFar?1/0:15,super.update()}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),super.dispose()}static Check(e){return e.isCamera}static Create(e){return new dP(e)}};_j([ae(),ei(v_.prototype.update)],v_.prototype,"showFar");let CI=v_;function cn(r,e,t,i,n,s,a,o){o.set(n,s,a).unproject(i);const l=e[r];if(l!==void 0){const c=t.getAttribute("instanceStart"),h=t.getAttribute("instanceEnd");for(let u=0,d=l.length;u<d;u++){const p=Math.floor(l[u]/2);(l[u]%2===0?c:h).setXYZ(p,o.x,o.y,o.z)}}}function bj(){const r=[],e=[],t={};i("u1","u2"),i("u2","u3"),i("u3","u1"),i("cn1","cn2"),i("cn3","cn4"),i("cf1","cf2"),i("cf3","cf4"),i("n1","n2"),i("n2","n4"),i("n4","n3"),i("n3","n1"),i("p","n1"),i("p","n2"),i("p","n3"),i("p","n4"),i("f1","f2"),i("f2","f4"),i("f4","f3"),i("f3","f1"),i("n1","f1"),i("n2","f2"),i("n3","f3"),i("n4","f4"),i("c","t"),i("p","c");function i(s,a){n(s),n(a)}function n(s){r.push(0,0,0),e.push(0,0,0),t[s]===void 0&&(t[s]=[]),t[s].push(r.length/3-1)}return{vertices:r,colors:e,pointMap:t}}var wj=Object.defineProperty,__=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&wj(e,t,n),n};const Dl=class fP extends Ig{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this._v1=new x,this._v2=new x,this._v3=new x,this.color=i,t!==void 0&&(this.size=t);let n=new vd;this.hMaterial=new ji({color:16711680,linewidth:3,vertexColors:!1,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lightPlane=new Vm(n,this.hMaterial),this.add(this.lightPlane),n=new vd,n.setPositions([0,0,0,0,0,1]),this.targetLine=new Vm(n,this.hMaterial),this.add(this.targetLine),this.update(),this.traverse(s=>{s.userData.__keepShadowDef=!0,s.castShadow=!1,s.receiveShadow=!1})}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose(),super.dispose()}update(){!this.light||!this.lightPlane||(this._v1.setFromMatrixPosition(this.light.matrixWorld),this._v2.setFromMatrixPosition(this.light.target.matrixWorld),this._v3.subVectors(this._v2,this._v1),this.lightPlane.geometry.setPositions([-this.size,this.size,0,this.size,this.size,0,this.size,-this.size,0,-this.size,-this.size,0,-this.size,this.size,0]),this.lightPlane.lookAt(this._v2),this.lightPlane.material=this.hMaterial,this.targetLine.material=this.hMaterial,this.hMaterial.color.set(this.color??this.light.color),this.hMaterial.linewidth=this.lineWidth,this.targetLine.lookAt(this._v2),this.targetLine.scale.z=this.light.intensity/3,super.update())}static Check(e){return e.isDirectionalLight}static Create(e){return new fP(e)}};__([de(Dl.prototype.update)],Dl.prototype,"hMaterial"),__([de(Dl.prototype.update),Oe(void 0,[.1,20],.01)],Dl.prototype,"lineWidth"),__([de(Dl.prototype.update),Oe(void 0,[.01,10],.01)],Dl.prototype,"size");let xI=Dl;var Cj=Object.defineProperty,Pg=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Cj(e,t,n),n};const Ia=class pP extends Ch{constructor(e){super(e),this._vertexHandles=[],this.handleSize=.05,this.editableHandleSize=.1,this.handleColor=37885,this.editableHandleColor=15663205,this.autoUpgradeChildren=!1,this.line=e,this._cubeGeometry=new mi(1,1,1,2,2,2),ri.upgradeGeometry.call(this._cubeGeometry),this._cubeMaterial=new ss({color:this.handleColor,transparent:!0,opacity:.95,allowOverride:!1}),this._cubeMaterial.userData.renderToGBuffer=!1,this._cubeMaterial.userData.renderToDepth=!1,this._cubeMaterial2=this._cubeMaterial.clone(),this._cubeMaterial2.color.set(this.editableHandleColor),this.update()}update(){if(super.update(),!this.line||!this.line.geometry)return;const e=this.line.geometry,t=e.getAttribute("position"),i=e.getPositions?e.getPositions():t?.array,n=i?i.length/3:0;if(!i||!n)return;const a=this.line.geometry.userData?.generationParams?.curve;if(a){const l=EI(a),c=this._vertexHandles;this._vertexHandles=[];for(let h=l.length;h<c.length;h++)this.remove(c[h]);for(let h=0;h<l.length;h++){const u=l[h],d=c[h]??new ye(this._cubeGeometry,this._cubeMaterial2);d.renderOrder=100;const p=u[0];isFinite(p[0])||(p[0]=0),isFinite(p[1])||(p[1]=0),isFinite(p[2])||(p[2]=0),d.position.fromArray(p),d.scale.setScalar(this.editableHandleSize),d.frustumCulled=!1,d.castShadow=!1,d.receiveShadow=!1,d.userData.__keepShadowDef=!0,d.parent||this.add(d),this._vertexHandles.push(d),d.userData.isWidgetHandle=!0,d.userData.transformControls={mode:"translate",space:"local",showX:!0,showY:!0,showZ:!0,lockProps:["mode"]},d.__handle=u,d.setDirty=m=>{if(m.change!=="transform")return;const A=d.__handle,g=A[0],y=A[1],_=d.position;if(Math.abs(g[0]-_.x)+Math.abs(g[1]-_.y)+Math.abs(g[2]-_.z)<=1e-4)return;g[0]=_.x,g[1]=_.y,g[2]=_.z;let b=a,T=y;if(T.startsWith("curves.")){const E=T.indexOf(".",7),M=parseInt(T.slice(7,E)||"0");T=T.slice(E+1),M>=0&&M<a.curves.length&&(b=a.curves[M])}if(T.startsWith("points.")){const E=parseInt(T.slice(7)||"0",10);b.points?.[E]?.set(g[0],g[1],g[2])}else b[T]?.set(g[0],g[1],g[2]);e.setDirty&&e.setDirty({regenerate:!0})}}if(l.length)return}this._clearVertexCubes();const o=this._vertexHandles;this._vertexHandles=[];for(let l=n;l<o.length;l++)this.remove(o[l]);for(let l=0;l<n;l++){const c=i[l*3],h=i[l*3+1],u=i[l*3+2],d=o[l]??new ye(this._cubeGeometry,this._cubeMaterial);d.position.set(isFinite(c)?c:0,isFinite(h)?h:0,isFinite(u)?u:0),d.scale.setScalar(this.handleSize),d.frustumCulled=!1,d.castShadow=!1,d.receiveShadow=!1,d.userData.__keepShadowDef=!0,d.parent||this.add(d),this._vertexHandles.push(d)}}_clearVertexCubes(){for(const e of this._vertexHandles)this.remove(e);this._vertexHandles=[]}dispose(){this._clearVertexCubes(),this._cubeGeometry.dispose(),this._cubeMaterial.dispose(),super.dispose()}static Check(e){return e.isLine||e.isLineSegments2}static Create(e){return new pP(e)}};Pg([de(Ia.prototype.update),Oe(void 0,[.001,.2],.001)],Ia.prototype,"handleSize"),Pg([de(Ia.prototype.update),Oe(void 0,[.001,.5],.001)],Ia.prototype,"editableHandleSize"),Pg([de(Ia.prototype.update),Tn()],Ia.prototype,"handleColor"),Pg([de(Ia.prototype.update),Tn()],Ia.prototype,"editableHandleColor");let SI=Ia;function EI(r){const e=[];return r.v0?.toArray&&e.push([r.v0.toArray(),"v0"]),r.v1?.toArray&&e.push([r.v1.toArray(),"v1"]),r.v2?.toArray&&e.push([r.v2.toArray(),"v2"]),r.v3?.toArray&&e.push([r.v3.toArray(),"v3"]),r.points!==void 0&&r.points.forEach((t,i)=>{e.push([t.toArray(),"points."+i])}),r.curves!==void 0&&r.curves.forEach((t,i)=>{const n=EI(t);n.forEach(s=>{s[1]="curves."+i+"."+s[1]}),e.push(...n)}),e}var xj=Object.defineProperty,b_=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&xj(e,t,n),n};const Rl=class mP extends Ig{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this.color=i,t!==void 0&&(this.size=t);const n=new f0(new Ds(.5,4,2));this.hMaterial=new ji({color:16711680,linewidth:3,vertexColors:!1,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lightSphere=new L1(n,this.hMaterial),this.lightSphere.computeLineDistances(),this.add(this.lightSphere),this.update(),this.traverse(s=>{s.userData.__keepShadowDef=!0,s.castShadow=!1,s.receiveShadow=!1})}dispose(){this.lightSphere.geometry.dispose(),this.lightSphere.material.dispose(),super.dispose()}update(){!this.light||!this.lightSphere||(this.hMaterial.color.set(this.color??this.light.color),this.hMaterial.linewidth=this.lineWidth,this.lightSphere.scale.setScalar(this.size),super.update())}static Check(e){return e.isPointLight}static Create(e){return new mP(e)}};b_([de(Rl.prototype.update)],Rl.prototype,"hMaterial"),b_([de(Rl.prototype.update),Oe(void 0,[.1,20],.01)],Rl.prototype,"lineWidth"),b_([de(Rl.prototype.update),Oe(void 0,[.01,10],.01)],Rl.prototype,"size");let MI=Rl;var Sj=Object.defineProperty,Qd=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Sj(e,t,n),n};const pr=class gP extends Ch{constructor(e,t,i){super(e),this._vector=new x,this._boneMatrix=new pe,this._matrixWorldInv=new pe,this.lineWidth=5,this.color1=new se(0,0,1),this.color2=new se(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i),this.bones=w_(e);const n=new Hs;this.hMaterial=new ji({vertexColors:!0,linewidth:this.lineWidth,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lineSegments=new _a(n,this.hMaterial),this.lineSegments.frustumCulled=!1,this.add(this.lineSegments),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.update()}updateMatrixWorld(e){this.object&&this.visible&&this.autoUpdate&&this.update(!1),super.updateMatrixWorld(e)}update(e=!0){if(!this.lineSegments||!this.object)return;this.hMaterial.linewidth=this.lineWidth;const t=this.lineSegments.geometry,i=[],n=[];for(const a of this.bones)a.parent&&a.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),n.push(this.color1.r,this.color1.g,this.color1.b),n.push(this.color2.r,this.color2.g,this.color2.b));this._matrixWorldInv.copy(this.object.matrixWorld).invert();let s=0;for(const a of this.bones)a.parent&&a.parent.isBone&&(this._boneMatrix.multiplyMatrices(this._matrixWorldInv,a.parent.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i[3*s]=this._vector.x,i[3*s+1]=this._vector.y,i[3*s+2]=this._vector.z,this._boneMatrix.multiplyMatrices(this._matrixWorldInv,a.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i[3*s+3]=this._vector.x,i[3*s+4]=this._vector.y,i[3*s+5]=this._vector.z,s+=2);i.length>0?(t.setPositions(i),t.setColors(n)):(t.setPositions([0,0,0,1,0,0]),t.setColors([1,0,0,0,1,0])),super.update(e)}dispose(){this.lineSegments.geometry.dispose(),this.lineSegments.material.dispose(),super.dispose()}static Check(e){let t=!1;return e.traverseAncestors(i=>{i._hasSkeletonHelper&&(t=!0)}),t?!1:w_(e).length>0}static Create(e){const t=new gP(e);return e._hasSkeletonHelper=!0,t}};Qd([ei(pr.prototype.update)],pr.prototype,"hMaterial"),Qd([ei(pr.prototype.update),Oe(void 0,[.1,20],.01)],pr.prototype,"lineWidth"),Qd([ei(pr.prototype.update),Tn()],pr.prototype,"color1"),Qd([ei(pr.prototype.update),Tn()],pr.prototype,"color2"),Qd([ae(),ei(pr.prototype.update)],pr.prototype,"autoUpdate");let TI=pr;function w_(r){const e=[];r.isBone===!0&&e.push(r);for(const t of r.children)e.push(...w_(t));return e}var Ej=Object.defineProperty,II=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Ej(e,t,n),n};const jd=class AP extends Ig{constructor(e,t,i){super(e),this.lineWidth=5,this._v1=new x,this.color=i;const n=new Hs,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let a=0,o=1,l=32;a<l;a++,o++){const c=a/l*Math.PI*2,h=o/l*Math.PI*2;s.push(Math.cos(c),Math.sin(c),1,Math.cos(h),Math.sin(h),1)}n.setPositions(s),this.hMaterial=new ji({color:16711680,linewidth:3,vertexColors:!1,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.cone=new _a(n,this.hMaterial),this.add(this.cone),this.update(),this.traverse(a=>{a.userData.__keepShadowDef=!0,a.castShadow=!1,a.receiveShadow=!1})}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose(),super.dispose()}update(){if(!this.light||!this.cone)return;this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1);const e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),this._v1.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(this._v1),this.hMaterial.color.set(this.color??this.light.color),this.hMaterial.linewidth=this.lineWidth,super.update()}static Check(e){return e.isSpotLight}static Create(e){return new AP(e)}};II([de(jd.prototype.update)],jd.prototype,"hMaterial"),II([de(jd.prototype.update),Oe(void 0,[.1,20],.01)],jd.prototype,"lineWidth");let PI=jd;const qr=class qr{constructor(){this._initialMatrix=new pe,this._chainActive=!1}onSelectionChanged(){this._chainActive=!1}onDuplicated(e){this._initialMatrix.copy(e),this._chainActive=!0}applyOffset(e,t,i="simple"){if(!this._chainActive)return!1;const n=qr._iP,s=qr._iQ,a=qr._iS;this._initialMatrix.decompose(n,s,a);const o=t.position.clone().sub(n),l=s.invert().premultiply(t.quaternion.clone()).normalize(),c=t.scale.clone().divide(a),h=o.lengthSq()>1e-10,u=Math.abs(l.x)>1e-6||Math.abs(l.y)>1e-6||Math.abs(l.z)>1e-6,d=Math.abs(c.x-1)>1e-6||Math.abs(c.y-1)>1e-6||Math.abs(c.z-1)>1e-6;if(!h&&!u&&!d)return!1;const p=i==="compound",m=qr._rel;for(const A of e)p?(m.copy(A.position).sub(n),d&&m.multiply(c),u&&m.applyQuaternion(l),A.position.copy(t.position).add(m)):h&&A.position.add(o),u&&A.quaternion.premultiply(l).normalize(),d&&A.scale.multiply(c),A.updateMatrixWorld(!0),A.setDirty?.({change:"transform"});return!0}saveState(){return{matrix:this._initialMatrix.clone(),active:this._chainActive}}restoreState(e){this._initialMatrix.copy(e.matrix),this._chainActive=e.active}reset(){this._initialMatrix.identity(),this._chainActive=!1}};qr._iP=new x,qr._iQ=new Qe,qr._iS=new x,qr._rel=new x;let Dg=qr;class DI{constructor(){this._state=null}get state(){return this._state}get isEmpty(){return!this._state}copy(e){const t=Ad(e);t.length&&(this._state={objects:t,mode:"copy",sourceParents:this._parentMap(t)})}cut(e){const t=Ad(e);t.length&&(this._state={objects:t,mode:"cut",sourceParents:this._parentMap(t)})}paste(e){return this._state?this._state.mode==="copy"?this._pasteFromCopy(e):this._pasteFromCut(e):null}clear(){this._state=null}_pasteFromCopy(e){const t=this._state;if(!t)return null;const i=[],n=new Map;for(const s of t.objects){const a=s.clone(!0);Nm(s,a);const o=e??s.parent;o&&(o.add(a),n.set(a,o)),i.push(a)}return{objects:i,undo:()=>{for(const s of i)s.removeFromParent()},redo:()=>{for(const s of i){const a=n.get(s);a&&!s.parent&&a.add(s)}}}}_pasteFromCut(e){const t=this._state;if(!t)return null;const i=t.objects,n=t.sourceParents;for(const s of i){const a=e??n.get(s);a&&s.parent!==a&&(s.removeFromParent(),a.add(s))}return this._state=null,{objects:i,undo:()=>{for(const s of i){const a=n.get(s);a&&s.parent!==a&&(s.removeFromParent(),a.add(s))}this._state=t},redo:()=>{for(const s of i){const a=e??n.get(s);a&&s.parent!==a&&(s.removeFromParent(),a.add(s))}this._state=null}}}_parentMap(e){const t=new Map;for(const i of e)t.set(i,i.parent);return t}}var Mj=Object.defineProperty,Wd=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Mj(e,t,n),n};function RI(r){for(;r.parent&&r.assetType!=="widget"&&!r.userData.allowPicking;)r=r.parent;return r}const bo=(Eo=class extends pt{constructor(e=wI,t=!0,i=!1){super(),this.enabled=!0,this._extraWidgets=[],this._clipboard=new DI,this._duplicateTracker=new Dg,this.duplicateMode="simple",this.dependencies=[n_],this.selectionMode="object",this.autoFocusHover=!1,this.autoApplyMaterialOnDrop=!0,this.widgetEnabled=!0,this.multiSelectEnabled=!0,this._onKeyDown=n=>{if(this.isDisabled()||n.target?.tagName==="TEXTAREA"||n.target?.tagName==="INPUT")return;const s=n.ctrlKey||n.metaKey;s&&n.code==="KeyA"?(n.preventDefault(),this.selectAll()):s&&n.code==="KeyD"?(n.preventDefault(),this.duplicateSelected(n.shiftKey?this.duplicateMode==="simple"?"compound":"simple":void 0)):s&&n.code==="KeyC"?(n.preventDefault(),this.copySelected()):s&&n.code==="KeyX"?(n.preventDefault(),this.cutSelected()):s&&n.code==="KeyV"?(n.preventDefault(),this.pasteFromClipboard()):n.code==="Escape"?this.clearSelection():n.code==="Delete"||n.code==="Backspace"?(n.preventDefault(),this.deleteSelected()):n.code==="KeyH"&&!s?(n.preventDefault(),n.shiftKey?this.unhideAll():this.toggleVisibilitySelected()):n.code==="KeyF"&&!s?(n.preventDefault(),this.focusSelected()):n.altKey&&!s&&(n.code==="KeyG"||n.code==="KeyR"||n.code==="KeyS")&&(n.preventDefault(),this.resetTransform(n.code==="KeyG"?"position":n.code==="KeyR"?"rotation":"scale"))},this._mainCameraChange=()=>{!this._picker||!this._viewer||(this._picker.camera=this._viewer.scene.mainCamera)},this._addSceneObject=n=>{n.object?.userData?.isWidgetRoot&&n.object.parent===this._viewer?.scene&&this._picker?.extraObjects.push(n.object)},this._sceneUpdate=n=>{if(n?.change==="removedFromParent"&&n.object?.userData?.isWidgetRoot&&this._picker){const s=this._picker.extraObjects.indexOf(n.object);s>=0&&this._picker.extraObjects.splice(s,1)}},this._objCompChange=n=>{n.object&&n.object===this.getSelectedObject()&&this.refreshUiChildren(n.object)},this._onObjectSelectEvent=n=>{n.source!==Eo.PluginType&&(n.object===void 0&&n.value===void 0?console.error("PickingPlugin - Error handling object/material `select` event `e.object` or `e.value` must be set for picking, `value` can be null to unselect"):this.setSelectedObject(n.object||n.value,this.autoFocus||n.focusCamera,n.trackUndo??!0))},this._selectedObjectChanged=n=>{if(!this._viewer)return;this._duplicateTracker.onSelectionChanged(),this.dispatchEvent(n);const s=this._picker?.selectedObject||void 0,a=this._viewer.getPlugin(f.FrameFadePlugin);a&&(s?a.disable(this):a.enable(this)),s?this._viewer.scene.disableAutoNearFar("PickingPlugin"):this._viewer.scene.enableAutoNearFar("PickingPlugin"),this.refreshUiChildren(s);const o=this._widget;o&&this.widgetEnabled&&(s?.isObject3D?o.attach(s):o.detach()),this._updateExtraWidgets(),this._viewer.setDirty(),this.autoFocus&&this.selectionMode==="object"&&this.focusObject(s)},this._hoverObjectChanged=n=>{if(!this._viewer)return;this.dispatchEvent(n);const s=this._picker?.hoverObject||void 0,a=this._hoverWidget;a&&this.widgetEnabled&&(s?.isObject3D?a.attach(s):a.detach()),this._viewer?.setDirty(),this.autoFocusHover&&this.selectionMode==="object"&&this.focusObject(s)},this._onObjectHit=n=>{if(!this._viewer)return;if(this.isDisabled()){n.intersects.selectedObject=null;return}let s=n.intersects.selectedObject;if(s){const a=s;s=RI(s),s.assetType==="widget"&&s.object&&(n.intersects.selectedObject=s.object,n.intersects.selectedWidget=s,n.intersects.selectedHandle=a.userData.isWidgetHandle?a:void 0)}this.dispatchEvent(n)},this._selectionModeChanged=n=>{this._viewer&&(this.dispatchEvent(n),!this.isDisabled()&&this.uiConfig?.uiRefresh?.(!0,"postFrame",1))},this._multiSelectChanged=n=>{if(this._viewer&&(this.dispatchEvent(n),!this.multiSelectEnabled&&this._picker&&this._picker.selectedObjects.length>1)){const s=this._picker.selectedObject;this._picker.setSelected(s,!1)}},this._onDrop=async n=>{if(!this._viewer||!this.autoApplyMaterialOnDrop)return;const a=n.assets?.find(l=>l.isMaterial),o=this.getSelectedObject();if(o&&o?.isObject3D&&a&&await this._viewer.dialog.confirm("Applying material: Apply material to the selected object?")){let l=o.material;Array.isArray(l)&&(console.warn("Dropping on material array not yet fully supported."),l=l[0]);let c=Array.from(l?.appliedMeshes??[]);(c.length>1?!await this._viewer.dialog.confirm("Applying material: Apply to all objects using this material?"):c.length<1)&&(c=[o]);for(const u of c)u&&(u.material=a)}},this._pickPromptUi={type:"button",label:"Select an object to see its properties",readOnly:!0,hidden:()=>this.getSelectedObject()!==void 0},this._uiConfigChildren=[{label:"Enabled",type:"checkbox",property:[this,"enabled"]},{label:"Hover Enabled",type:"checkbox",property:[this,"hoverEnabled"],onChange:()=>this.uiConfig.uiRefresh?.(!0)},{label:"Auto Focus",type:"checkbox",property:[this,"autoFocus"],onChange:()=>{const n=this.getSelectedObject();this.autoFocus&&n&&this.setSelectedObject(n,!0)}},{label:"Auto Focus on Hover",type:"checkbox",hidden:()=>!this.hoverEnabled,property:[this,"autoFocusHover"]},{label:"Widget Enabled",type:"checkbox",property:[this,"widgetEnabled"]},{label:"Multi-Select",type:"checkbox",property:[this,"multiSelectEnabled"]},{label:"Duplicate Mode",type:"dropdown",property:[this,"duplicateMode"],children:["simple","compound"].map(n=>({label:n,value:n}))}],this.uiConfig={type:"folder",label:"Picker",expanded:!0,children:[...this._uiConfigChildren,this._pickPromptUi]},this.canRemoveMaterial=n=>{if(!n.material)return!1;const s=Array.isArray(n.material)?n.material:n.material?[n.material]:[];return s.length&&(s.length!==1||!s[0].userData?.isPlaceholder)},this.removeMaterial=n=>{if(!n.material)return;const s=n.material;return n.material=this.getPlaceholderMaterial(n),()=>n.material=s},this.materialTypes=[{cls:ys,def:Bs.DummyMaterial,name:"Unlit"},{cls:$n,def:Bs.DummyLineBasicMaterial,line:!0,name:"Basic Line"},{cls:ji,def:Bs.DummyLineMaterial,line:!0,name:"Line"},{cls:ai,name:"Physical"}],this._selectionWidgetClass=e,e&&(this._widget=new e,this._hoverWidget=new e,this._hoverWidget.lineMaterial&&(this._hoverWidget.lineMaterial.linewidth/=2,this._hoverWidget.lineMaterial.color.set("#aa2222"))),this._pickUi=t,this.autoFocus=i,this.dispatchEvent=this.dispatchEvent.bind(this)}get picker(){return this._picker}get hoverEnabled(){return this._picker?.hoverEnabled??!1}set hoverEnabled(e){this._picker&&(this._picker.hoverEnabled=e,this.uiConfig&&this.uiConfig.uiRefresh?.())}_widgetEnabledChange(){this._widget&&(this.widgetEnabled&&this._picker?.selectedObject?.isObject3D?this._widget.attach(this._picker.selectedObject):this._widget.detach(),this._updateExtraWidgets(),this.uiConfig?.uiRefresh?.(!0))}_updateExtraWidgets(){if(!this._viewer||!this._selectionWidgetClass)return;const t=(this._picker?.selectedObjects||[]).filter((i,n)=>n>0&&i?.isObject3D);for(let i=t.length;i<this._extraWidgets.length;i++)this._extraWidgets[i].detach();for(let i=0;i<t.length;i++){if(!this._extraWidgets[i]){const n=new this._selectionWidgetClass;n.lineMaterial&&(n.lineMaterial.color.set("#ff8844"),n.lineMaterial.opacity=.7),this._extraWidgets.push(n),this._viewer.scene.addObject(n,{addToRoot:!0})}this.widgetEnabled?this._extraWidgets[i].attach(t[i]):this._extraWidgets[i].detach()}}setDirty(){this._viewer&&(this.isDisabled()&&this.getSelectedObject()&&this.setSelectedObject(void 0),this._viewer.setDirty())}getSelectedObject(){return this._picker?.selectedObject||void 0}getSelectedObjects(){return this._picker?.selectedObjects||[]}toggleSelectedObject(e){if(!this._picker||this.isDisabled()||!e||!this.multiSelectEnabled)return;const t=[...this._picker.selectedObjects],i=t.indexOf(e);i>=0?t.splice(i,1):t.unshift(e),this._picker.setSelected(t.length?t.length===1?t[0]:t:null,!0)}selectAll(){if(!this._picker||!this._viewer||this.isDisabled()||!this.multiSelectEnabled)return;const e=[];this._viewer.scene.modelRoot.traverse(t=>{t.isObject3D&&t.visible&&t.assetType==="model"&&t.userData.userSelectable!==!1&&t.material&&e.push(t)}),e.length&&this._picker.setSelected(e.length===1?e[0]:e,!0)}clearSelection(){this._picker&&this._picker.setSelected(null,!0)}_setSelectedFromArray(e){!e||!e.length?this._picker?.setSelected(null,!1):e.length===1?this._picker?.setSelected(e[0],!1):this._picker?.setSelected(e,!1)}async deleteSelected(){const e=this.getSelectedObjects().filter(n=>n?.isObject3D);if(!e.length)return;const t=await xM(e);if(!t)return;const i=[...e];this._setSelectedFromArray(null),this._undoManager?.record({undo:()=>{t.undo(),this._setSelectedFromArray(i)},redo:()=>{this._setSelectedFromArray(null),t.redo()}})}duplicateSelected(e){const t=e??this.duplicateMode,i=this.getSelectedObjects().filter(h=>h?.isObject3D);if(!i.length)return;const{clones:n,undo:s,redo:a}=SM(i);if(!n.length)return;const o=this._duplicateTracker.saveState(),l=new pe().compose(n[0].position,n[0].quaternion,n[0].scale);this._duplicateTracker.applyOffset(n,i[0],t),this._setSelectedFromArray(n),this._duplicateTracker.onDuplicated(l);const c=[...i];this._undoManager?.record({undo:()=>{s(),this._setSelectedFromArray(c),this._duplicateTracker.restoreState(o)},redo:()=>{a(),this._setSelectedFromArray(n),this._duplicateTracker.onDuplicated(l)}})}copySelected(){const e=this.getSelectedObjects().filter(t=>t?.isObject3D);e.length&&this._clipboard.copy(e)}cutSelected(){const e=this.getSelectedObjects().filter(t=>t?.isObject3D);e.length&&this._clipboard.cut(e)}pasteFromClipboard(){if(this._clipboard.isEmpty)return;const e=this._getPasteDestination(),t=this._clipboard.paste(e);if(!t)return;const i=this.getSelectedObjects();this._setSelectedFromArray(t.objects),this._viewer?.setDirty();const{objects:n,undo:s,redo:a}=t;this._undoManager?.record({undo:()=>{s(),this._setSelectedFromArray(i),this._viewer?.setDirty()},redo:()=>{a(),this._setSelectedFromArray(n),this._viewer?.setDirty()}})}_getPasteDestination(){const e=this.getSelectedObject();return e?.isObject3D?this._isContainer(e)?e:e.parent:null}_isContainer(e){return!e.material&&!e.geometry&&!e.isLight&&!e.isCamera&&e.assetType!=="light"&&e.assetType!=="camera"&&e.assetType!=="widget"}toggleVisibilitySelected(){const e=this.getSelectedObjects().filter(s=>s?.isObject3D);if(!e.length)return;const i=!e[0].visible,n=new Map;for(const s of e)n.set(s,s.visible);for(const s of e)s.visible=i,s.setDirty?.();this._viewer?.setDirty(),this._undoManager?.record({undo:()=>{for(const[s,a]of n)s.visible=a,s.setDirty?.();this._viewer?.setDirty()},redo:()=>{for(const s of e)s.visible=i,s.setDirty?.();this._viewer?.setDirty()}})}unhideAll(){if(!this._viewer)return;const e=[];if(this._viewer.scene.modelRoot.traverse(t=>{t.isObject3D&&!t.visible&&e.push(t)}),!!e.length){for(const t of e)t.visible=!0,t.setDirty?.();this._viewer.setDirty(),this._undoManager?.record({undo:()=>{for(const t of e)t.visible=!1,t.setDirty?.();this._viewer?.setDirty()},redo:()=>{for(const t of e)t.visible=!0,t.setDirty?.();this._viewer?.setDirty()}})}}focusSelected(){const e=this.getSelectedObjects().filter(t=>t?.isObject3D);e.length&&this.focusObject(e.length===1?e[0]:e)}resetTransform(e){const t=this.getSelectedObjects().filter(s=>s?.isObject3D);if(!t.length)return;const i=t.map(s=>({obj:s,position:s.position.clone(),quaternion:s.quaternion.clone(),scale:s.scale.clone()})),n=()=>{for(const s of t)e==="position"?s.position.set(0,0,0):e==="rotation"?s.quaternion.identity():s.scale.set(1,1,1),s.updateMatrixWorld(!0),s.setDirty?.({change:"transform"});this._viewer?.setDirty()};n(),this._undoManager?.record({undo:()=>{for(const s of i)s.obj.position.copy(s.position),s.obj.quaternion.copy(s.quaternion),s.obj.scale.copy(s.scale),s.obj.updateMatrixWorld(!0),s.obj.setDirty?.({change:"transform"});this._viewer?.setDirty()},redo:()=>{n()}})}setSelectedObject(e,t=!1,i=!0){const n=this.isDisabled();if(n&&e||!this._picker)return;const s=this.autoFocus;this.autoFocus=!1,this._picker.setSelected(e||null,i),this.autoFocus=s,!n&&e&&this.selectionMode==="object"&&(s||t)&&this.focusObject(e)}onAdded(e){super.onAdded(e),this.setDirty(),this._picker=new XS(e.scene.modelRoot,e.canvas,e.scene.mainCamera,t=>{if(!t.material&&!t.userData.userSelectable)return!1;let n=t;n=RI(n);let s=!1;for(;n;){if(!n.visible||((n.assetType==="model"||n.assetType==="light")&&(s=!0),n.userData.userSelectable===!1)||n.userData.bboxVisible===!1)return!1;n=n.parent}return s}),this._picker.extraObjects.push(...e.scene.children.filter(t=>t.userData.isWidgetRoot)),this._viewer?.scene.addEventListener("addSceneObject",this._addSceneObject),this._viewer?.scene.addEventListener("sceneUpdate",this._sceneUpdate),this._widget&&e.scene.addObject(this._widget,{addToRoot:!0}),this._hoverWidget&&e.scene.addObject(this._hoverWidget,{addToRoot:!0}),this._picker.addEventListener("selectedObjectChanged",this._selectedObjectChanged),this._picker.addEventListener("hoverObjectChanged",this._hoverObjectChanged),this._picker.addEventListener("hitObject",this._onObjectHit),this._picker.addEventListener("selectionModeChanged",this._selectionModeChanged),this._picker.addEventListener("multiSelectChanged",this._multiSelectChanged),window.addEventListener("keydown",this._onKeyDown),e.scene.addEventListener("select",this._onObjectSelectEvent),e.scene.addEventListener("materialChanged",this._objCompChange),e.scene.addEventListener("geometryChanged",this._objCompChange),e.scene.addEventListener("texturesChanged",this._objCompChange),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),e.forPlugin("DropzonePlugin",t=>{t.addEventListener("drop",this._onDrop)},t=>{t.removeEventListener("drop",this._onDrop)}),e.forPlugin("UndoManagerPlugin",t=>{this._picker&&(this._picker.undoManager=t.undoManager,this._undoManager=t.undoManager)},()=>{this._picker&&(this._picker.undoManager=void 0,this._undoManager=void 0)},this)}onRemove(e){window.removeEventListener("keydown",this._onKeyDown),e.scene.removeEventListener("select",this._onObjectSelectEvent),e.scene.removeEventListener("materialChanged",this._objCompChange),e.scene.removeEventListener("geometryChanged",this._objCompChange),e.scene.removeEventListener("texturesChanged",this._objCompChange),e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.scene.removeEventListener("sceneUpdate",this._sceneUpdate),this._widget?.removeFromParent(),this._hoverWidget?.removeFromParent();for(const t of this._extraWidgets)t.removeFromParent();this._extraWidgets=[],this._picker&&(this._picker.removeEventListener("selectedObjectChanged",this._selectedObjectChanged),this._picker.removeEventListener("hoverObjectChanged",this._hoverObjectChanged),this._picker.removeEventListener("hitObject",this._onObjectHit),this._picker.removeEventListener("selectionModeChanged",this._selectionModeChanged),this._picker.removeEventListener("multiSelectChanged",this._multiSelectChanged),this._picker.dispose(),this._picker.undoManager=void 0,this._picker=void 0),this._undoManager=void 0,this._clipboard.clear(),this._duplicateTracker.reset(),super.onRemove(e)}dispose(){super.dispose(),this._widget?.dispose?.(),this._hoverWidget?.dispose?.();for(const e of this._extraWidgets)e.dispose?.();this._extraWidgets=[]}async focusObject(e){this._viewer?.fitToView(e??void 0,1.25,1e3,"easeOut")}get widget(){return this._widget}refreshUiChildren(e){if(this._pickUi){const t=this.uiConfig;if(t.children=[...this._uiConfigChildren],e){if(e.isObject3D){const l=e;t.children.push(...this.objectSelectionUiConfig(l))}const i=e.uiConfig;i?.type==="folder"&&an(i,"expanded",!0,!0),i&&t.children.push(i);const n=e?.isObject3D?e:void 0,s=e?.isMaterial?e:n?.material,a=s?Array.isArray(s)?s:[s]:[],o=e?.isBufferGeometry?e:n?.geometry;if(o?.uiConfig&&o!==e){const l=o.uiConfig;l.type==="folder"&&an(l,"expanded",!0,!0),t.children.push(l)}a.forEach(l=>{l?.uiConfig&&l!==e&&t.children?.push(l.uiConfig)}),e.isObject3D&&t.children.push(...this.objectMaterialManageUiConfig(e))}else t.children.push(this._pickPromptUi);t.uiRefresh?.()}}objectSelectionUiConfig(e){return[{type:"button",label:"Focus",value:()=>{e.isObject3D&&(e.assetType&&e.parentRoot?e.dispatchEvent({type:"select",ui:!0,object:e,bubbleToParent:!0,focusCamera:!0}):this.setSelectedObject(e,!0))}},{type:"button",label:"Select Parent",hidden:()=>!e.parent,value:()=>{if(!e.isObject3D)return;const t=e.parent;t&&(t.assetType&&t.parentRoot?t.dispatchEvent({type:"select",ui:!0,bubbleToParent:!0,object:t}):this.setSelectedObject(t,!1))}}]}objectMaterialManageUiConfig(e){return[{label:"Remove Material(s)",type:"button",hidden:()=>!this.canRemoveMaterial(e),value:()=>this.removeMaterial(e)},...this.materialTypes.map(t=>({label:`New ${t.name} Material`,type:"button",hidden:t.line?(()=>!e.isLineSegments2&&!e.isLine&&!e.isLineSegments&&!e.isWireframe||!(!e.materials?.length||e.materials.length===1&&e.materials[0]===t.def)):()=>!(!e.materials?.length||e.materials.length===1&&e.materials[0].userData?.isPlaceholder)||!e.isMesh,value:()=>{const i=e.material;return e.material=new t.cls,()=>e.material=i}}))]}getPlaceholderMaterial(e){const t=[this.materialTypes[0].def];if(!t[0])throw new Error("No default material found");const i=e.isLineSegments2||e.isWireframe?this.materialTypes.find(n=>n.cls===ji)?.def:e.isLine||e.isLineSegments?this.materialTypes.find(n=>n.cls===$n)?.def:null;return i||t[0]}},Eo.PluginType="Picking",Eo.OldPluginType="PickingPlugin",Eo);Wd([z(),de(bo.prototype.setDirty)],bo.prototype,"enabled"),Wd([Vt({obj:"_picker",key:"selectionMode"})],bo.prototype,"selectionMode"),Wd([z()],bo.prototype,"autoFocus"),Wd([de(bo.prototype._widgetEnabledChange)],bo.prototype,"widgetEnabled"),Wd([Vt({obj:"_picker",key:"multiSelectEnabled"})],bo.prototype,"multiSelectEnabled");let ws=bo;class BI{constructor(){this.multiObjects=[],this._dummy=null,this._dummyStart=new pe,this._startStates=[],this._startWorldMatrices=[]}get dummy(){return this._dummy}get hasMultiSelect(){return this.multiObjects.length>1}get hasStartStates(){return this._startStates.length>0}setup(e,t){this.multiObjects=e,this._dummy||(this._dummy=new ft,this._dummy.userData.isMultiSelectDummy=!0,t.scene.addObject(this._dummy,{addToRoot:!0}));const i=new x;for(const n of e)n.updateWorldMatrix(!0,!1),i.add(new x().setFromMatrixPosition(n.matrixWorld));return i.divideScalar(e.length),this._dummy.position.copy(i),this._dummy.quaternion.identity(),this._dummy.scale.setScalar(1),this._dummy.updateMatrixWorld(!0),this._dummy}clear(e){this.multiObjects=[],this._startStates=[],this._startWorldMatrices=[],this._dummy&&(e.scene.remove(this._dummy),this._dummy=null)}captureStart(){!this._dummy||!this.multiObjects.length||(this._dummy.updateMatrixWorld(!0),this._dummyStart.copy(this._dummy.matrixWorld),this._startStates=this.multiObjects.map(e=>({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})),this._startWorldMatrices=this.multiObjects.map(e=>(e.updateWorldMatrix(!0,!1),e.matrixWorld.clone())))}applyDelta(){if(!this._dummy||!this.multiObjects.length||!this._startWorldMatrices.length)return;this._dummy.updateMatrixWorld(!0);const e=this._dummyStart.clone().invert(),t=this._dummy.matrixWorld.clone().multiply(e);for(let i=0;i<this.multiObjects.length;i++){const n=this.multiObjects[i],s=t.clone().multiply(this._startWorldMatrices[i]),a=new pe;n.parent&&a.copy(n.parent.matrixWorld).invert(),a.clone().multiply(s).decompose(n.position,n.quaternion,n.scale),n.updateMatrixWorld(!0),n.setDirty?.({change:"transform",frameFade:!1})}}updateDummyPosition(){if(!this._dummy||!this.multiObjects.length)return;const e=new x;for(const t of this.multiObjects)t.updateWorldMatrix(!0,!1),e.add(new x().setFromMatrixPosition(t.matrixWorld));e.divideScalar(this.multiObjects.length),this._dummy.position.copy(e),this._dummy.quaternion.identity(),this._dummy.scale.setScalar(1),this._dummy.updateMatrixWorld(!0)}recordUndo(e){if(!this.multiObjects.length||!this._startStates.length)return;const t=[...this.multiObjects],i=this._startStates.map(a=>({position:a.position.clone(),quaternion:a.quaternion.clone(),scale:a.scale.clone()})),n=t.map(a=>({position:a.position.clone(),quaternion:a.quaternion.clone(),scale:a.scale.clone()}));let s=!1;for(let a=0;a<t.length;a++)if(!i[a].position.equals(n[a].position)||!i[a].quaternion.equals(n[a].quaternion)||!i[a].scale.equals(n[a].scale)){s=!0;break}s&&e.record({undo:()=>{for(let a=0;a<t.length;a++)t[a].position.copy(i[a].position),t[a].quaternion.copy(i[a].quaternion),t[a].scale.copy(i[a].scale),t[a].updateMatrixWorld(!0),t[a].setDirty?.({change:"transform"});this.updateDummyPosition()},redo:()=>{for(let a=0;a<t.length;a++)t[a].position.copy(n[a].position),t[a].quaternion.copy(n[a].quaternion),t[a].scale.copy(n[a].scale),t[a].updateMatrixWorld(!0),t[a].setDirty?.({change:"transform"});this.updateDummyPosition()}})}}var Tj=Object.defineProperty,Ij=Object.getOwnPropertyDescriptor,mr=(r,e,t,i)=>{for(var n=i>1?void 0:i?Ij(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Tj(e,t,n),n};f.TransformControlsPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[ws],this._isInteracting=!1,this._viewerListeners={postFrame:()=>{!this.transformControls||this._viewer}},this._transformState={obj:null,position:new x,rotation:new Tt,scale:new x},this.selectionFilterTest=void 0,this._multi=new BI,this._mainCameraChange=()=>{!this.transformControls||!this._viewer||(this.transformControls.camera=this._viewer.scene.mainCamera)},cr.ObjectConstructors.MeshBasicMaterial=ys,cr.ObjectConstructors.LineBasicMaterial=$n,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(ws),t=!this.isDisabled();if(this.transformControls)if(!t)this.transformControls.detach(),this._multi.clear(this._viewer);else{const i=e.getSelectedObjects().filter(n=>n?.isObject3D);i.length>1?this.transformControls.attach(this._multi.setup(i,this._viewer)):i.length===1?(this._multi.clear(this._viewer),this.transformControls.attach(i[0])):(this._multi.clear(this._viewer),this.transformControls.detach())}this._viewer.setDirty()}onAdded(e){super.onAdded(e),this.setDirty(),this.transformControls=new f.TransformControls2(e.scene.mainCamera,e.canvas),this._mainCameraChange=this._mainCameraChange.bind(this),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),this.transformControls.addEventListener("dragging-changed",i=>{if(!this?._viewer)return;const n=this._viewer.scene.mainCamera.controls;typeof n?.stopDamping=="function"&&n?.enabled&&n.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!i.value,f.TransformControlsPlugin.PluginType)}),this.transformControls.addEventListener("axis-changed",i=>{if(!this?._viewer)return;this._isInteracting=!!i.value;const n=this._viewer.scene.mainCamera.controls;typeof n?.stopDamping=="function"&&n?.enabled&&n.stopDamping(),this._viewer.setDirty()}),e.scene.addObject(this.transformControls,{addToRoot:!0}),e.getPlugin(ws).addEventListener("selectedObjectChanged",i=>{if(!this.transformControls)return;if(this.isDisabled()){this.transformControls.object&&this.transformControls.detach(),this._multi.clear(this._viewer);return}const n=(i.objects||[]).filter(s=>s?.isObject3D);if(n.length>1)this.transformControls.attach(this._multi.setup(n,this._viewer));else if(i.object){this._multi.clear(this._viewer);let s=i.intersects?.selectedHandle??i.intersects?.selectedObject??i.object;if(this.selectionFilterTest&&(s=this.selectionFilterTest(s)),!s||!s.isObject3D){this.transformControls.detach();return}this.transformControls.attach(s)}else this._multi.clear(this._viewer),this.transformControls.detach()}),e.forPlugin("UndoManagerPlugin",i=>{this.undoManager=i.undoManager},()=>this.undoManager=void 0,this),this.transformControls.addEventListener("mouseDown",()=>{if(!this.transformControls)return;if(this._multi.hasMultiSelect){this._multi.captureStart();return}const i=this.transformControls.object;i&&(this._transformState.obj=i,this._transformState.position=i.position.clone(),this._transformState.rotation=i.rotation.clone(),this._transformState.scale=i.scale.clone())}),this.transformControls.addEventListener("objectChange",()=>{this._multi.hasMultiSelect&&this._multi.applyDelta()}),this.transformControls.addEventListener("mouseUp",()=>{if(!this.transformControls)return;if(this._multi.hasMultiSelect&&this._multi.hasStartStates){this.undoManager&&this._multi.recordUndo(this.undoManager);return}const i=this.transformControls.object;if(!i||this._transformState.obj!==i||!this.undoManager)return;const n={translate:"position",rotate:"rotation",scale:"scale"}[this.transformControls.getMode()];if(!n||this._transformState[n].equals(i[n]))return;const s={last:this._transformState[n].clone(),current:i[n].clone(),set:a=>{i[n].copy(a),i.updateMatrixWorld(!0),this.transformControls?.dispatchEvent({type:"change"}),this.transformControls?.dispatchEvent({type:"objectChange"})},undo:()=>s.set(s.last),redo:()=>s.set(s.current)};this.undoManager.record(s)})}onRemove(e){e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),this._multi.clear(e),this.transformControls&&(this.transformControls.detach(),e.scene.remove(this.transformControls),this.transformControls.dispose()),this.transformControls=void 0,super.onRemove(e)}centerAllMeshes(){return this._viewer?.scene.centerAllGeometries(!0)}},f.TransformControlsPlugin.PluginType="TransformControlsPlugin",mr([ae(),de(f.TransformControlsPlugin.prototype.setDirty)],f.TransformControlsPlugin.prototype,"enabled",2),mr([Li(void 0,{expanded:!0})],f.TransformControlsPlugin.prototype,"transformControls",2),mr([lt("Center All Meshes")],f.TransformControlsPlugin.prototype,"centerAllMeshes",1),f.TransformControlsPlugin=mr([gt("Transform Controls")],f.TransformControlsPlugin),f.TransformControls2=class extends cr{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=Ge.setDirty.bind(this),this.refreshUi=Ge.refreshUi.bind(this),this.lockProps=void 0,this._savedSettings={},this.visible=!1,this.userData.bboxVisible=!1,this.size=1.25,this.addEventListener("objectChange",()=>{this?.object?.setDirty&&this.object.setDirty({frameFade:!1,change:"transform"})}),this.addEventListener("change",()=>{this.setDirty({frameFade:!1})}),this._keyUpListener=this._keyUpListener.bind(this),this._keyDownListener=this._keyDownListener.bind(this),window.addEventListener("keydown",this._keyDownListener),window.addEventListener("keyup",this._keyUpListener),this.traverse(i=>{i.castShadow=!1,i.receiveShadow=!1,i.userData.__keepShadowDef=!0})}_keyDownListener(e){if(!this.enabled||!this.object)return;if(!IS(e,{toggleSpace:()=>{this.space=this.space==="local"?"world":"local"},adjustSize:i=>{this.size=Math.max(this.size+i,.1)},toggleAxis:i=>{i===0?this.showX=!this.showX:i===1?this.showY=!this.showY:this.showZ=!this.showZ},toggleEnabled:()=>{this.enabled=!this.enabled}})){if(e.metaKey||e.ctrlKey||e.target?.tagName==="TEXTAREA"||e.target?.tagName==="INPUT")return;switch(e.code){case"ShiftLeft":case"ShiftRight":this.translationSnap=.5,this.rotationSnap=Ut.degToRad(15),this.scaleSnap=.25;break;case"KeyW":this.mode="translate";break;case"KeyE":this.mode="rotate";break;case"KeyR":this.mode="scale";break;default:return}}this.setDirty({refreshScene:!0,frameFade:!0})}_keyUpListener(e){if(this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.translationSnap=null,this.rotationSnap=null,this.scaleSnap=null;break}this.object&&e.code}}attach(e){let t=!1;if(this.traverseAncestors(i=>t=t||i===e),t)return this;if(this._savedSettings.lockProps&&(this.lockProps=this._savedSettings.lockProps),Object.assign(this,this._savedSettings),this._savedSettings={},e.userData.transformControls){const i=["translationSnap","rotationSnap","scaleSnap","space","mode","showX","showY","showZ","lockProps"];for(const n of i)e.userData.transformControls[n]!==void 0&&(this._savedSettings[n]=this[n],this[n]=e.userData.transformControls[n])}return super.attach(e)}detach(){return this._savedSettings.lockProps&&(this.lockProps=this._savedSettings.lockProps),Object.assign(this,this._savedSettings),this._savedSettings={},super.detach()}dispose(){window.removeEventListener("keydown",this._keyDownListener),window.removeEventListener("keyup",this._keyUpListener),super.dispose()}get modelObject(){return this}},mr([Oi("Mode",["translate","rotate","scale"].map(r=>({label:r})))],f.TransformControls2.prototype,"mode",2),mr([Oi("Space",["world","local"].map(r=>({label:r})))],f.TransformControls2.prototype,"space",2),mr([Oe("Size",[.1,10],.01)],f.TransformControls2.prototype,"size",2),mr([ae("Show X")],f.TransformControls2.prototype,"showX",2),mr([ae("Show Y")],f.TransformControls2.prototype,"showY",2),mr([ae("Show Z")],f.TransformControls2.prototype,"showZ",2),f.TransformControls2=mr([gt("Transform Controls")],f.TransformControls2);var Pj=Object.defineProperty,Dj=Object.getOwnPropertyDescriptor,Gn=(r,e,t,i)=>{for(var n=i>1?void 0:i?Dj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Pj(e,t,n),n};f.PivotControlsPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[ws],this._isInteracting=!1,this._viewerListeners={preFrame:()=>{!this.pivotControls||!this._viewer||this.pivotControls.updateGizmoScale()}},this._transformState={obj:null,position:new x,rotation:new Tt,scale:new x},this.selectionFilterTest=void 0,this._multi=new BI,this._mainCameraChange=()=>{!this.pivotControls||!this._viewer||(this.pivotControls.camera=this._viewer.scene.mainCamera)},Qc.ObjectConstructors.MeshBasicMaterial=ys,Qc.ObjectConstructors.LineBasicMaterial=$n,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(ws),t=!this.isDisabled();if(this.pivotControls)if(!t)this.pivotControls.detach(),this._multi.clear(this._viewer);else{const i=e.getSelectedObjects().filter(n=>n?.isObject3D);i.length>1?this.pivotControls.attach(this._multi.setup(i,this._viewer)):i.length===1?(this._multi.clear(this._viewer),this.pivotControls.attach(i[0])):(this._multi.clear(this._viewer),this.pivotControls.detach())}this._viewer.setDirty()}onAdded(e){super.onAdded(e),this.setDirty(),this.pivotControls=new f.PivotControls2(e.scene.mainCamera,e.canvas),this._mainCameraChange=this._mainCameraChange.bind(this),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),this.pivotControls.addEventListener("dragging-changed",i=>{if(!this?._viewer)return;const n=this._viewer.scene.mainCamera.controls;typeof n?.stopDamping=="function"&&n?.enabled&&n.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!i.value,f.PivotControlsPlugin.PluginType)}),this.pivotControls.addEventListener("change",()=>{this?._viewer&&this._viewer.setDirty()}),e.scene.addObject(this.pivotControls,{addToRoot:!0}),e.getPlugin(ws).addEventListener("selectedObjectChanged",i=>{if(!this.pivotControls)return;if(this.isDisabled()){this.pivotControls.object&&this.pivotControls.detach(),this._multi.clear(this._viewer);return}const n=(i.objects||[]).filter(s=>s?.isObject3D);if(n.length>1)this.pivotControls.attach(this._multi.setup(n,this._viewer));else if(i.object){this._multi.clear(this._viewer);let s=i.intersects?.selectedHandle??i.intersects?.selectedObject??i.object;if(this.selectionFilterTest&&(s=this.selectionFilterTest(s)),!s||!s.isObject3D){this.pivotControls.detach();return}this.pivotControls.attach(s)}else this._multi.clear(this._viewer),this.pivotControls.detach()}),e.forPlugin("UndoManagerPlugin",i=>{this.undoManager=i.undoManager},()=>this.undoManager=void 0,this),this.pivotControls.addEventListener("mouseDown",()=>{if(!this.pivotControls)return;if(this._multi.hasMultiSelect){this._multi.captureStart();return}const i=this.pivotControls.object;i&&(this._transformState.obj=i,this._transformState.position=i.position.clone(),this._transformState.rotation=i.rotation.clone(),this._transformState.scale=i.scale.clone())}),this.pivotControls.addEventListener("objectChange",()=>{this._multi.hasMultiSelect&&this._multi.applyDelta()}),this.pivotControls.addEventListener("mouseUp",i=>{if(!this.pivotControls)return;if(this._multi.hasMultiSelect&&this._multi.hasStartStates){this.undoManager&&this._multi.recordUndo(this.undoManager);return}const n=this.pivotControls.object;if(!n||this._transformState.obj!==n||!this.undoManager)return;const s=i.mode,a={translate:"position",rotate:"rotation",scale:"scale"}[s];if(!a||this._transformState[a].equals(n[a]))return;const o={last:this._transformState[a].clone(),current:n[a].clone(),set:l=>{n[a].copy(l),n.updateMatrixWorld(!0),this.pivotControls?.dispatchEvent({type:"change"}),this.pivotControls?.dispatchEvent({type:"objectChange"})},undo:()=>o.set(o.last),redo:()=>o.set(o.current)};this.undoManager.record(o)})}onRemove(e){e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),this._multi.clear(e),this.pivotControls&&(this.pivotControls.detach(),e.scene.remove(this.pivotControls),this.pivotControls.dispose()),this.pivotControls=void 0,super.onRemove(e)}},f.PivotControlsPlugin.PluginType="PivotControlsPlugin",Gn([ae(),de(f.PivotControlsPlugin.prototype.setDirty)],f.PivotControlsPlugin.prototype,"enabled",2),Gn([Li(void 0,{expanded:!0})],f.PivotControlsPlugin.prototype,"pivotControls",2),f.PivotControlsPlugin=Gn([gt("Pivot Controls")],f.PivotControlsPlugin),f.PivotControls2=class extends Qc{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=Ge.setDirty.bind(this),this.refreshUi=Ge.refreshUi.bind(this),this.visible=!1,this.userData.bboxVisible=!1,this.addEventListener("objectChange",()=>{this?.object?.setDirty&&this.object.setDirty({frameFade:!1,change:"transform"})}),this.addEventListener("change",()=>{this.setDirty({frameFade:!1})}),this.traverse(i=>{i.castShadow=!1,i.receiveShadow=!1,i.userData.__keepShadowDef=!0})}_onVisibilityChange(){this.updateHandleVisibility(),this.setDirty&&this.setDirty({frameFade:!1})}_onRebuild(){this.domElement&&(this.rebuild(),this.setDirty&&this.setDirty({frameFade:!1}))}get modelObject(){return this}},Gn([Oi("Space",["world","local"].map(r=>({label:r}))),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"space",2),Gn([Oe("Gizmo Scale",[.1,10],.01),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"gizmoScale",2),Gn([ae("Fixed Size"),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"fixed",2),Gn([ae("Depth Test"),de(f.PivotControls2.prototype._onRebuild)],f.PivotControls2.prototype,"depthTest",2),Gn([ae("Annotations")],f.PivotControls2.prototype,"annotations",2),Gn([Oe("Translation Snap",[.01,5],.01)],f.PivotControls2.prototype,"translationSnap",2),Gn([Oe("Rotation Snap (deg)",[1,90],1)],f.PivotControls2.prototype,"rotationSnap",2),Gn([Oe("Scale Snap",[.01,1],.01)],f.PivotControls2.prototype,"scaleSnap",2),Gn([ae("Uniform Scale (Alt)")],f.PivotControls2.prototype,"uniformScaleEnabled",2),Gn([ae("Disable Axes"),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableAxes",2),Gn([ae("Disable Sliders"),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableSliders",2),Gn([ae("Disable Rotations"),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableRotations",2),Gn([ae("Disable Scaling"),de(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableScaling",2),f.PivotControls2=Gn([gt("Pivot Controls")],f.PivotControls2);var Rj=Object.defineProperty,Bj=Object.getOwnPropertyDescriptor,Pa=(r,e,t,i)=>{for(var n=i>1?void 0:i?Bj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Rj(e,t,n),n};const C_=new x,LI=new x;f.PivotEditPlugin=class extends pt{constructor(e=!0){super(),this.dependencies=[ws],this.enabled=!0,this.editPivot=!1,this.showPivotMarker=!0,this.markerScale=.5,this.markerColor=16776960,this.toJSON=void 0,this._pivotGizmo=null,this._markerRoot=null,this._markerWidget=null,this._pivotMarker=null,this._selectedObject=null,this._viewerListeners={preFrame:()=>this._updateMarker()},this._onKeyDown=null,this.enabled=e}onAdded(e){super.onAdded(e);const t=e.getPlugin(ws);t.addEventListener("hitObject",s=>{s.intersects?.selectedHandle?.userData.isPivotMarker&&(s.intersects.consumed=!0,this.editPivot=!this.editPivot,this._onEditPivotChange())}),t.addEventListener("selectedObjectChanged",s=>{const a=s.object,o=a!==this._selectedObject;this._selectedObject=a,this._markerWidget&&(this._markerWidget.object=this._selectedObject),this.editPivot&&o&&(this.editPivot=!1,this._onEditPivotChange()),this._updateMarker()}),e.forPlugin("UndoManagerPlugin",s=>{this.undoManager=s.undoManager},()=>this.undoManager=void 0,this),this._onKeyDown=s=>{this.isDisabled()||s.metaKey||s.ctrlKey||s.target?.tagName==="TEXTAREA"||s.target?.tagName==="INPUT"||(s.code==="KeyP"?(this.editPivot=!this.editPivot,this._onEditPivotChange()):s.code==="Escape"&&this.editPivot&&(this.editPivot=!1,this._onEditPivotChange()))},window.addEventListener("keydown",this._onKeyDown);const i=new ss({color:this.markerColor,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,opacity:.9});this._pivotMarker=new ye(new Ds(1,8,8),i),this._pivotMarker.renderOrder=1e3,this._pivotMarker.userData.isWidgetHandle=!0,this._pivotMarker.userData.isPivotMarker=!0;const n=new Al;n.isWidget=!0,n.assetType="widget",n.object=this._selectedObject,n.attach=s=>(n.object=s,n),n.detach=()=>(n.object=void 0,n),this._markerWidget=n,this._markerWidget.add(this._pivotMarker),this._markerRoot=new Al,this._markerRoot.userData.isWidgetRoot=!0,this._markerRoot.add(this._markerWidget),this._markerRoot.visible=!1,this._markerRoot.traverse(s=>{s.castShadow=!1,s.receiveShadow=!1,s.userData.__keepShadowDef=!0}),e.scene.addObject(this._markerRoot,{addToRoot:!0})}onRemove(e){this._onKeyDown&&(window.removeEventListener("keydown",this._onKeyDown),this._onKeyDown=null),this._destroyGizmo(e),this._markerRoot&&(e.scene.remove(this._markerRoot),this._pivotMarker&&(this._pivotMarker.geometry.dispose(),this._pivotMarker.material.dispose()),this._markerRoot=null,this._markerWidget=null,this._pivotMarker=null),super.onRemove(e)}pivotToCenter(){this._selectedObject?.pivotToBoundsCenter&&(this._recordUndo(this._selectedObject.pivotToBoundsCenter(!0)),this._refreshAfterPivotChange())}pivotToBottom(){if(!this._selectedObject?.pivotToPoint)return;const e=new In().expandByObject(this._selectedObject,!0,!0),t=e.getCenter(new x);this._applyPivot(new x(t.x,e.min.y,t.z))}pivotToOrigin(){this._applyPivot(new x(0,0,0))}pivotToPoint(e){this._applyPivot(e)}_applyPivot(e){if(!this._selectedObject?.pivotToPoint)return;const t=this._selectedObject.pivotToPoint(e,!0);this._recordUndo(t),this._refreshAfterPivotChange()}_updateMarker(){if(!this._markerRoot||!this._pivotMarker||!this._viewer)return;if(this.isDisabled()||!this.showPivotMarker||!this._selectedObject){this._markerRoot.visible=!1;return}this._selectedObject.updateWorldMatrix(!0,!1),C_.setFromMatrixPosition(this._selectedObject.matrixWorld),this._markerRoot.position.copy(C_),this._markerRoot.visible=!0;const e=this._viewer.scene.mainCamera;let t;e.isOrthographicCamera?t=(e.top-e.bottom)/e.zoom:(LI.setFromMatrixPosition(e.matrixWorld),t=C_.distanceTo(LI)*Math.min(1.9*Math.tan(Math.PI*e.fov/360)/e.zoom,7)),this._pivotMarker.scale.setScalar(t*this.markerScale*.05)}_onEditPivotChange(){this._viewer&&(this.editPivot?this._attachGizmo():this._detachGizmo(),this._viewer.setDirty())}_attachGizmo(){if(!this._viewer||!this._selectedObject)return;this._setTransformControlsEnabled(!1),this._pivotGizmo||(cr.ObjectConstructors.MeshBasicMaterial=ys,cr.ObjectConstructors.LineBasicMaterial=$n,this._pivotGizmo=new cr(this._viewer.scene.mainCamera,this._viewer.canvas),this._pivotGizmo.setMode("translate"),this._pivotGizmo.userData.bboxVisible=!1,this._pivotGizmo.visible=!1,this._pivotGizmo.traverse(t=>{t.castShadow=!1,t.receiveShadow=!1,t.userData.__keepShadowDef=!0}),this._pivotGizmo.addEventListener("mouseUp",()=>{if(!this._selectedObject?.pivotToPoint||!this._pivotGizmo?.object)return;const t=new x().setFromMatrixPosition(this._pivotGizmo.object.matrixWorld),i=this._selectedObject.pivotToPoint(t,!0);this._recordUndo(i),this._refreshAfterPivotChange()}),this._pivotGizmo.addEventListener("change",()=>{this._viewer&&this._viewer.setDirty()}),this._pivotGizmo.addEventListener("dragging-changed",t=>{if(!this._viewer)return;const i=this._viewer.scene.mainCamera.controls;typeof i?.stopDamping=="function"&&i?.enabled&&i.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!t.value,f.PivotEditPlugin.PluginType)}),this._viewer.scene.addObject(this._pivotGizmo,{addToRoot:!0})),this._selectedObject.updateWorldMatrix(!0,!1);const e=new x().setFromMatrixPosition(this._selectedObject.matrixWorld);if(this._pivotGizmo.object)this._pivotGizmo.object.position.copy(e),this._pivotGizmo.object.updateMatrixWorld(!0);else{const t=new ft;t.position.copy(e),this._viewer.scene.addObject(t,{addToRoot:!0}),this._pivotGizmo.attach(t)}}_detachGizmo(){if(this._pivotGizmo){const e=this._pivotGizmo.object;this._pivotGizmo.detach(),e&&this._viewer&&this._viewer.scene.remove(e)}this._setTransformControlsEnabled(!0)}_destroyGizmo(e){this._pivotGizmo&&(this._detachGizmo(),e.scene.remove(this._pivotGizmo),this._pivotGizmo.dispose(),this._pivotGizmo=null)}_setTransformControlsEnabled(e){if(!this._viewer)return;const t=this._viewer.getPlugin("TransformControlsPlugin");t&&(e?t.setDirty():t.transformControls?.detach());const i=this._viewer.getPlugin("PivotControlsPlugin");i&&(e?i.setDirty():i.pivotControls?.detach())}_onEnabledChange(){this.isDisabled()&&this.editPivot&&(this.editPivot=!1,this._onEditPivotChange()),this._updateMarker(),this._viewer&&this._viewer.setDirty()}_refreshAfterPivotChange(){this._viewer&&(this.editPivot&&this._selectedObject&&this._pivotGizmo?.object&&(this._selectedObject.updateWorldMatrix(!0,!1),this._pivotGizmo.object.position.setFromMatrixPosition(this._selectedObject.matrixWorld),this._pivotGizmo.object.updateMatrixWorld(!0)),this._updateMarker(),this._viewer.setDirty())}_onDirty(){this._viewer&&this._viewer.setDirty()}_onMarkerColorChange(){this._pivotMarker&&this._pivotMarker.material.color.set(this.markerColor),this._viewer&&this._viewer.setDirty()}_recordUndo(e){if(!this.undoManager||!this._selectedObject)return;const t=this._selectedObject;t.updateWorldMatrix(!0,!1);const i=new x().setFromMatrixPosition(t.matrixWorld);this.undoManager.record({undo:()=>{e(),this._refreshAfterPivotChange()},redo:()=>{t.pivotToPoint&&(t.pivotToPoint(i,!0),this._refreshAfterPivotChange())}})}},f.PivotEditPlugin.PluginType="PivotEditPlugin",Pa([ae(),de(f.PivotEditPlugin.prototype._onEnabledChange)],f.PivotEditPlugin.prototype,"enabled",2),Pa([ae("Edit Pivot"),de(f.PivotEditPlugin.prototype._onEditPivotChange)],f.PivotEditPlugin.prototype,"editPivot",2),Pa([ae("Show Pivot Marker"),de(f.PivotEditPlugin.prototype._onDirty)],f.PivotEditPlugin.prototype,"showPivotMarker",2),Pa([Oe("Marker Scale",[.1,5],.1),de(f.PivotEditPlugin.prototype._onDirty)],f.PivotEditPlugin.prototype,"markerScale",2),Pa([Tn("Marker Color"),de(f.PivotEditPlugin.prototype._onMarkerColorChange)],f.PivotEditPlugin.prototype,"markerColor",2),Pa([lt("Pivot to Center")],f.PivotEditPlugin.prototype,"pivotToCenter",1),Pa([lt("Pivot to Bottom")],f.PivotEditPlugin.prototype,"pivotToBottom",1),Pa([lt("Pivot to Origin")],f.PivotEditPlugin.prototype,"pivotToOrigin",1),f.PivotEditPlugin=Pa([gt("Pivot Edit")],f.PivotEditPlugin);var Lj=Object.defineProperty,Oj=Object.getOwnPropertyDescriptor,OI=(r,e,t,i)=>{for(var n=i>1?void 0:i?Oj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Lj(e,t,n),n};f.EditorViewWidgetPlugin=class extends pt{constructor(e="top-left",t=128){super(),this.placement=e,this.size=t,this.enabled=!0,this._needsRender=!1,this._viewerListeners={postRender:i=>{!this._viewer||!this.widget||this.isDisabled()||(this._needsRender=!0)},postFrame:i=>{!this._viewer||!this.widget||this.isDisabled()||!this._needsRender||(this.widget.update(),this.widget.render(),this.widget.animating&&this._viewer.scene.mainCamera.setDirty(),this._needsRender=!1)}},this.setDirty=this.setDirty.bind(this),this._mainCameraChange=this._mainCameraChange.bind(this),this._mainCameraUpdate=this._mainCameraUpdate.bind(this)}setDirty(){!this._viewer||!this.widget||(this.widget.domContainer.style.display=this.isDisabled()?"none":"block")}onAdded(e){super.onAdded(e),this.widget=new Uv(e.scene.mainCamera,e.canvas,this.placement,this.size),this.widget.target=e.scene.mainCamera.target,this.widget.addEventListener("animating-changed",t=>{const i=t.detail.value;e.scene.mainCamera.setInteractions(!i,f.EditorViewWidgetPlugin.PluginType)}),this.widget.addEventListener("update",()=>this._needsRender=!0),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),e.scene.addEventListener("mainCameraUpdate",this._mainCameraUpdate)}onRemove(e){this.widget?.dispose(),this.widget=void 0,e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),e.scene.removeEventListener("mainCameraUpdate",this._mainCameraUpdate),super.onRemove(e)}_mainCameraChange(){!this._viewer||!this.widget||(this.widget.camera=this._viewer.scene.mainCamera)}_mainCameraUpdate(){!this._viewer||!this.widget||(this.widget.target=this._viewer.scene.mainCamera.target)}setOrientation(e){this.widget&&this.widget.setOrientation(e)}},f.EditorViewWidgetPlugin.PluginType="EditorViewWidgetPlugin",OI([ae(),de(f.EditorViewWidgetPlugin.prototype.setDirty)],f.EditorViewWidgetPlugin.prototype,"enabled",2),f.EditorViewWidgetPlugin=OI([gt("Editor View Widget")],f.EditorViewWidgetPlugin);const nb=class nb extends xg{constructor(){super(...arguments),this.controlsKey="deviceOrientation",this._controlsCtor=(e,t)=>new f.DeviceOrientationControls2(e)}};nb.PluginType="DeviceOrientationControlsPlugin";let x_=nb;const sb=class sb extends xg{constructor(){super(...arguments),this.controlsKey="pointerLock",this._controlsCtor=(e,t)=>new f.PointerLockControls2(e,t?.ownerDocument?t:(t||document).documentElement)}};sb.PluginType="PointerLockControlsPlugin";let S_=sb;const rb=class rb extends xg{constructor(){super(...arguments),this.controlsKey="threeFirstPerson",this._controlsCtor=(e,t)=>new f.FirstPersonControls2(e,t||document.documentElement)}};rb.PluginType="ThreeFirstPersonControlsPlugin";let E_=rb;var Uj=Object.defineProperty,UI=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Uj(e,t,n),n};const qd=(Hh=class extends pt{constructor(e=!0,t=1e3){super(),this.enabled=!0,this.limit=1e3,this.toJSON=void 0,this.undoEditingWaitTime=2e3,this.undoCommandTypes={setValue:"ThreeViewerUM_set",action:"ThreeViewerUM_action"},this.undoPresets={[this.undoCommandTypes.setValue]:i=>{const n=()=>{i.onUndoRedo&&i.onUndoRedo(i)};return{undo:()=>{console.log("undo",i.lastVal),i.binding&&(this.setValue(i.binding,i.lastVal,i.props,i.uid,void 0,!1),n())},redo:()=>{i.binding&&(this.setValue(i.binding,i.val,i.props,i.uid,void 0,!1),n())}}},[this.undoCommandTypes.action]:i=>{const n=()=>{i.onUndoRedo&&i.onUndoRedo(i)};return{undo:async()=>{await i.undo.call(i.target,...i.args),n()},redo:async()=>{await i.redo.call(i.target,...i.args),n()}}}},this.enabled=e,this.limit=t}undo(){this.undoManager?.undo()}redo(){this.undoManager?.redo()}_refresh(){this.undoManager&&(this.undoManager.enabled=this.enabled,this.undoManager.limit=this.limit,this.undoManager.options.debug=this._viewer?.debug||this.undoManager.options.debug,this.undoManager&&Object.assign(this.undoManager.presets,this.undoPresets))}onAdded(e){super.onAdded(e),this.undoManager=new Hy({bindHotKeys:!0,limit:this.limit,debug:e.debug||Vu("debugUndo")!==null,hotKeyRoot:document}),this._refresh()}onRemove(e){this.undoManager?.dispose(),this.undoManager=void 0,super.onRemove(e)}recordUndo(e){return Yp(this.undoManager,e,this.undoCommandTypes.setValue,this.undoEditingWaitTime)}async performAction(e,t,i,n,s){const a=()=>e===void 0?t(...i):t.call(e,...i);let o=await a();const l=typeof o=="function"?o:o?.undo?.bind(o),c=typeof o!="function"?o?.action?.bind(o):null,h=typeof o=="function"?a:o?.redo?.bind(o)??c;typeof c=="function"&&(o=await c()),typeof l=="function"&&this.recordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:l,redo:h,args:i,onUndoRedo:s})}setValue(e,t,i,n,s,a=!0,o){return!(!iv(this.undoManager,e,t,i,n,this.undoCommandTypes.setValue,a,this.undoEditingWaitTime,!0,o).undoable&&!s)}setValues(e,t,i,n,s,a,o=!0,l){const c=FI(e,t);return this.setValue([c,"value"],i,n,s,a,o,l)}},Hh.PluginType="UndoManagerPlugin",Hh);UI([de(qd.prototype._refresh)],qd.prototype,"enabled"),UI([de(qd.prototype._refresh)],qd.prototype,"limit");let Fj=qd;function FI(r,e){return{p:new Proxy([],{get(t,i,...n){if(i==="length")return r.length;const s=Number(i);if(isNaN(s)||s<0||s>=r.length)return Reflect.get(Array.prototype,i,...n)||Reflect.get(t,i,...n);const[a,o]=r[s];return a?.[o]??e[s]},set(t,i,n,...s){const a=Number(i);if(isNaN(a)||a<0||a>=r.length)return Reflect.set(t,i,n,...s);const[o,l]=r[a];return o?(o[l]=n,!0):!1},has(t,i,...n){const s=Number(i);return isNaN(s)||s<0||s>=r.length?Reflect.has(Array.prototype,i,...n)||Reflect.has(t,i,...n):!0}}),get value(){return this.p},set value(t){r.length!==t.length&&console.error(`UndoManager - setValues: bindings length (${r.length}) does not match value length (${t.length})`);for(let i=0;i<Math.min(t.length,r.length);i++)this.p[i]=t[i]}}}var Nj=Object.defineProperty,kj=Object.getOwnPropertyDescriptor,Bl=(r,e,t,i)=>{for(var n=i>1?void 0:i?kj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Nj(e,t,n),n};f.Rhino3dmLoadPlugin=class extends Pl{constructor(){super(...arguments),this._importer=new qi(ur,["3dm"],["model/vnd.3dm","model/3dm"],!0),this.importMaterials=!0,this.forceLayerMaterials=!1,this.replaceWithInstancedMesh=!1,this.hideLineMesh=!1,this.hidePointMesh=!0,this.loadUserDataStrings=!0}_refresh(){ur.ImportMaterials=this.importMaterials,ur.ForceLayerMaterials=this.forceLayerMaterials,ur.ReplaceWithInstancedMesh=this.replaceWithInstancedMesh,ur.HideLineMesh=this.hideLineMesh,ur.HidePointMesh=this.hidePointMesh,ur.LoadUserDataStrings=this.loadUserDataStrings,ur.LoadUserDataWarnings=!1}onAdded(e){if(!window.WebAssembly)throw new Error("Rhino3dmLoadPlugin requires WebAssembly support");super.onAdded(e),this._refresh()}},f.Rhino3dmLoadPlugin.PluginType="Rhino3dmLoadPlugin",Bl([de(f.Rhino3dmLoadPlugin.prototype._refresh),ae()],f.Rhino3dmLoadPlugin.prototype,"importMaterials",2),Bl([de(f.Rhino3dmLoadPlugin.prototype._refresh),ae()],f.Rhino3dmLoadPlugin.prototype,"forceLayerMaterials",2),Bl([de(f.Rhino3dmLoadPlugin.prototype._refresh),ae()],f.Rhino3dmLoadPlugin.prototype,"replaceWithInstancedMesh",2),Bl([de(f.Rhino3dmLoadPlugin.prototype._refresh),ae()],f.Rhino3dmLoadPlugin.prototype,"hideLineMesh",2),Bl([de(f.Rhino3dmLoadPlugin.prototype._refresh),ae()],f.Rhino3dmLoadPlugin.prototype,"hidePointMesh",2),Bl([de(f.Rhino3dmLoadPlugin.prototype._refresh),ae()],f.Rhino3dmLoadPlugin.prototype,"loadUserDataStrings",2),f.Rhino3dmLoadPlugin=Bl([gt("Rhino 3dm Loader")],f.Rhino3dmLoadPlugin);const ab=class ab extends Pl{constructor(){super(...arguments),this._importer=new qi(class extends iI{constructor(){super(...arguments),this.currentUrl=""}async loadAsync(e,t){this.currentUrl=e;const i=await super.loadAsync(e,t);if(this.currentUrl="",!i.children.length)throw new Error("No mesh found in USDZ file, note that usdc files are not supported.");return i}parse(e){if(this.currentUrl.endsWith(".usda")&&typeof e!="string"){const t=this.currentUrl.split("/").pop();if(t){const i={};i[t]=new Uint8Array(e),e=hg(i).buffer}}return super.parse(e)}},["usdz","usda"],["model/vnd.usd+zip","model/vnd.usdz+zip","model/vnd.usda"],!1)}};ab.PluginType="USDZLoadPlugin";let M_=ab;const ob=class ob extends Pl{constructor(){super(...arguments),this._importer=new qi(class extends nI{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new ye(e,new ai({color:new se(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["ply"],["text/plain+ply"],!1)}};ob.PluginType="PLYLoadPlugin";let T_=ob;const lb=class lb extends Pl{constructor(){super(...arguments),this._importer=new qi(class extends sI{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new ye(e,new ai({color:new se(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["stl"],["model/stl","model/x.stl-binary","model/x.stl-ascii"],!1)}};lb.PluginType="STLLoadPlugin";let I_=lb;const cb=class cb extends Pl{constructor(){super(...arguments),this._importer=new qi(tI,["ktx"],["image/ktx"],!1)}};cb.PluginType="KTXLoadPlugin";let P_=cb;const Qh=class Qh extends Pl{constructor(){super(...arguments),this._importer=new qi(NI,["ktx2"],["image/ktx2"],!1)}onAdded(e){this._importer.onCtor=t=>t.setTranscoderPath(Qh.TRANSCODER_LIBRARY_PATH).detectSupport(e.renderManager.renderer),super.onAdded(e),e.assetManager.exporter.getExporter("gltf","glb")?.extensions?.push(kI)}onRemove(e){const t=e.assetManager.exporter.getExporter("gltf","glb"),i=t?.extensions?.indexOf(kI);i!==void 0&&i!==-1&&t?.extensions?.splice(i,1),super.onRemove(e)}};Qh.PluginType="KTX2LoadPlugin",Qh.TRANSCODER_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/BinomialLLC/basis_universal@1.16.4/webgl/transcoder/build/",Qh.SAVE_SOURCE_BLOBS=!1;let Xd=Qh;class NI extends dr{_initTexture(e){bd.call(e),e.userData.mimeType="image/ktx2",e.toJSON=i=>mE(e,i,e.name,"image/ktx2");const t=e.clone;return e.clone=()=>{const i=t.call(e);return i.source!==e.source&&(i.source._sourceImgBuffer=e.source._sourceImgBuffer),this._initTexture(i)},e}async createTexture(e,t){const i=Xd.SAVE_SOURCE_BLOBS?new Uint8Array(e.slice(0)):void 0,n=await super.createTexture(e,t);return Xd.SAVE_SOURCE_BLOBS&&i&&(n.source._sourceImgBuffer=i,n.source._canSerialize=!0),this._initTexture(n),n}}const D_="KHR_texture_basisu",kI=r=>({writeTexture:(e,t)=>{if(e.userData.mimeType!=="image/ktx2")return;if(t.source!==void 0&&t.source!==null){console.warn("ktx2 export: source already set");return}const i=e.source._sourceImgBuffer||e.__sourceBuffer;if(!i){console.warn("ktx2 export: no source buffer for ktx2");return}t.extensions=t.extensions||{};const n={},s=new Blob([i],{type:"image/ktx2"});n.source=r.processImageBlob(s,e),t.extensions[D_]=n,r.extensionsUsed[D_]=!0}}),ef=class ef extends Qp{constructor(e=!0,t=document.head){super(),this.rootNode=t,this.enabled=!0,this.toJSON=void 0,this._initializing=void 0,e&&this.initialize()}get initialized(){return!!window.MeshoptDecoder}async initialize(){if(this.initialized)return;if(this._initializing)return await this._initializing;const e=document.createElement("script");e.type="module";const t=Math.random().toString(36).substring(7);e.innerHTML=`
import { MeshoptDecoder } from ${JSON.stringify(ef.DECODER_URL)};
window.MeshoptDecoder = MeshoptDecoder; // setting it before ready as GLTFLoader supports it.
MeshoptDecoder.ready.then(() => {
window.dispatchEvent(new CustomEvent('${t}'))
});
`,this._initializing=new Promise(i=>{window.addEventListener(t,()=>i(),{once:!0}),this.rootNode.appendChild(e),this._script=e}),await this._initializing,this.dispatchEvent({type:"initialized"})}dispose(){this._script&&(this._script.remove(),delete window.MeshoptDecoder),this._script=void 0}onAdded(){}onRemove(){}};ef.PluginType="GLTFMeshOptDecodePlugin",ef.DECODER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_decoder.module.js";let R_=ef;var Gj=Object.defineProperty,zj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Gj(e,t,n),n};const hb=class hb extends pt{constructor(){super(),this.enabled=!0,this.exportOptions={name:"scene",viewerConfig:!0,encodeUint16Rgbe:!1,convertMeshToIndexed:!1,embedUrlImagePreviews:!1,embedUrlImages:!1,encrypt:!1,encryptKey:"",ignoreInvalidMorphTargetTracks:!0,ignoreEmptyTextures:!0},this.uiConfig={type:"folder",label:"Asset Export",expanded:!0,children:[{type:"input",property:[this.exportOptions,"name"]},{type:"folder",label:"GLB Export",expanded:!0,children:[{type:"checkbox",label:"Viewer Config (All Settings)",property:[this.exportOptions,"viewerConfig"],onChange:()=>this.uiConfig.uiRefresh?.(!0)},{type:"checkbox",label:"Embed Image Previews",property:[this.exportOptions,"embedUrlImagePreviews"]},{type:"checkbox",label:"Encrypt",property:[this.exportOptions,"encrypt"],onChange:()=>this.uiConfig.uiRefresh?.(!0)},{type:"input",label:"Encrypt Password",hidden:()=>!this.exportOptions.encrypt,property:[this.exportOptions,"encryptKey"]},{type:"checkbox",label:"Compress hdr env maps",hidden:()=>!this.exportOptions.viewerConfig,property:[this.exportOptions,"encodeUint16Rgbe"]},{type:"checkbox",label:"Ignore invalid animations",property:[this.exportOptions,"ignoreInvalidMorphTargetTracks"]},{type:"checkbox",label:"Ignore invalid textures",property:[this.exportOptions,"ignoreInvalidTextures"]},{type:"button",label:"Export GLB",property:[this,"downloadSceneGlb"]}]},{type:"button",label:"Export Config",value:async()=>{const e=new Blob([JSON.stringify(this._viewer?.exportConfig(!1),null,2)],{type:"application/json"});e&&await this._viewer?.exportBlob(e,this.exportOptions.name+"."+f.ThreeViewer.ConfigTypeSlug)}},{type:"button",label:"Export Selected",hidden:()=>!this._viewer?.getPlugin("PickingPlugin"),value:async()=>this.exportSelected(this.exportOptions,!0)}]},this.exportScene=this.exportScene.bind(this)}onAdded(e){super.onAdded(e)}onRemove(e){return super.onRemove(e)}async exportScene(e){return this._viewer?.assetManager.exporter?.exportObject(this._viewer?.scene.modelRoot,e||{...this.exportOptions})}async downloadSceneGlb(){const e=await this.exportScene(this.exportOptions);e&&await this._viewer?.exportBlob(e,this.exportOptions.name+"."+e.ext)}async exportSelected(e,t=!0){const i=this._viewer?.getPlugin("PickingPlugin")?.getSelectedObject();if(!i){this._viewer?.dialog.alert("Export Selected: Nothing selected");return}const n=i.name||"selected",s=await this._viewer.assetManager.exporter.exportObject(i,e??this.exportOptions);return s&&t&&await this._viewer?.exportBlob(s,n+"."+s.ext),s}};hb.PluginType="AssetExporterPlugin";let Rg=hb;zj([z()],Rg.prototype,"exportOptions");var Vj=Object.defineProperty,Hj=Object.getOwnPropertyDescriptor,xh=(r,e,t,i)=>{for(var n=i>1?void 0:i?Hj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Vj(e,t,n),n};f.CanvasSnapshotPlugin=class extends pt{constructor(){super(),this.enabled=!0,this.filename="snapshot",this._downloading=!1,this.defaultOptions={waitForProgressive:!0,displayPixelRatio:window.devicePixelRatio,scale:1,timeout:0,quality:.9,tileRows:1,tileColumns:1,progressiveFrames:64,rect:{x:0,y:0,width:1,height:1,normalized:!0,assumeClientRect:!1}},this.downloadSnapshot=this.downloadSnapshot.bind(this)}async getFile(e,t={waitForProgressive:!0}){return await this._getFile(e||this.filename,{...t,getDataUrl:!1})}async getDataUrl(e={}){return await this._getFile("",{...e,getDataUrl:!0})??""}async _getFile(e,t={}){await this._viewer?.doOnce("postFrame");const i=this._viewer,n=this._viewer?.canvas;if(!i||!n)return;i.scene.mainCamera.setInteractions(!1,f.CanvasSnapshotPlugin.PluginType);const s=i.renderManager.renderScale;t.displayPixelRatio!==void 0&&t.displayPixelRatio!==s&&(i.renderManager.renderScale=t.displayPixelRatio),t.timeout&&await jn(t.timeout);const a=i.getPlugin(f.ProgressivePlugin);let o=t.waitForProgressive??!!a;o&&!a&&(i.console.warn("CanvasSnapshotPlugin: ProgressivePlugin required to wait for progressive rendering"),o=!1),t.progressiveFrames&&!o&&i.console.warn("CanvasSnapshotPlugin: waitForProgressive must be true to use progressiveFrames");const l=a?.maxFrameCount;if(o&&a)for(a.maxFrameCount=Math.max(t.progressiveFrames??64,a.maxFrameCount),i.setDirty(),await i.doOnce("postFrame");!a.isConverged(!0);)await i.doOnce("postFrame");else i.setDirty(),await i.doOnce("postFrame");delete t.displayPixelRatio;let c;if(t.tileRows&&t.tileRows>1||t.tileColumns&&t.tileColumns>1){const h=await md.GetTiledFiles(n,e,Math.max(1,t.tileRows||1),Math.max(1,t.tileColumns||1),t);if(Array.isArray(h))if(h.length===1)c=h[0];else if(h.length===0)c=void 0;else if(t.getDataUrl)c=h;else{const u={};for(const p of h)u[p.name]=new Uint8Array(await p.arrayBuffer());const d=hg(u);c=new File([d],e+".zip",{type:"application/zip",lastModified:Date.now()})}else c=h}else c=await md.GetFile(n,e,t);return t.displayPixelRatio=i.renderManager.renderScale,a&&l!==void 0&&(a.maxFrameCount=l),i.scene.mainCamera.setInteractions(!0,f.CanvasSnapshotPlugin.PluginType,!1),i.renderManager.renderScale=s,c}async downloadSnapshot(e,t={waitForProgressive:!0}){if(!this._viewer)return;for(;this._downloading;)console.warn("CanvasSnipperPlugin: Another rendering already in progress, waiting..."),await jn(100);this._downloading=!0;const i=await this.getFile(e,{...this.defaultOptions,...t}).catch(n=>(this._viewer?.console.error("CanvasSnapshotPlugin: Error exporting file",n),null));i&&await this._viewer.exportBlob(i,i.name),this._downloading=!1}async _downloadPng(){return this.downloadSnapshot(void 0,{mimeType:"image/png"})}async _downloadJpeg(){return this.downloadSnapshot(void 0,{mimeType:"image/jpeg"})}async _downloadWebp(){return this.downloadSnapshot(void 0,{mimeType:"image/webp"})}},f.CanvasSnapshotPlugin.PluginType="CanvasSnapshotPlugin",xh([Fe("Filename"),z()],f.CanvasSnapshotPlugin.prototype,"filename",2),xh([Li(void 0,{label:"Options"}),z()],f.CanvasSnapshotPlugin.prototype,"defaultOptions",2),xh([lt("Download .png")],f.CanvasSnapshotPlugin.prototype,"_downloadPng",1),xh([lt("Download .jpeg")],f.CanvasSnapshotPlugin.prototype,"_downloadJpeg",1),xh([lt("Download .webp")],f.CanvasSnapshotPlugin.prototype,"_downloadWebp",1),f.CanvasSnapshotPlugin=xh([gt("Image Export (Canvas Snapshot)")],f.CanvasSnapshotPlugin);const ub=class ub extends f.CanvasSnapshotPlugin{constructor(){super(),console.warn("CanvasSnipperPlugin is deprecated, use CanvasSnapshotPlugin")}};ub.PluginType="CanvasSnipper";let B_=ub;const db=class db extends pt{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this.defaultActions={exportFile:async(e,t,i)=>{ku(e,t)}},this.actions={...this.defaultActions},this._updateProcessState=this._updateProcessState.bind(this)}async exportFile(e,t){t=t||e.name||"file_export",this.dispatchEvent({type:"transferFile",path:t,state:"exporting",progress:0}),await this.actions.exportFile(e,t,({state:i,progress:n})=>{this.dispatchEvent({type:"transferFile",path:t,state:i??"exporting",progress:n})}),this.dispatchEvent({type:"transferFile",path:t,state:"done"})}onAdded(e){super.onAdded(e),this.addEventListener("transferFile",this._updateProcessState)}onRemove(e){this.removeEventListener("transferFile",this._updateProcessState),super.onRemove(e)}_updateProcessState(e){this._viewer&&this._viewer.assetManager.setProcessState(e.path,e.state!=="done"?{state:e.state,progress:e.progress?e.progress*100:void 0}:void 0)}};db.PluginType="FileTransferPlugin";let L_=db;const Qj="vec4 Vignette(in vec4 color){vec2 uv=vUv*(1.0-vUv);float vig=uv.x*uv.y*16.0;vig=pow(vig,power);return vec4(mix(color.rgb,vec3(bgcolor),1.-vig),color.a);}";var jj=Object.defineProperty,Wj=Object.getOwnPropertyDescriptor,Bg=(r,e,t,i)=>{for(var n=i>1?void 0:i?Wj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&jj(e,t,n),n};f.VignettePlugin=class extends Gd{constructor(e=!0){super(),this.extraUniforms={power:{value:1},bgcolor:{value:new se}},this.power=.5,this.color=new se(0),this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float power;
            uniform vec3 bgcolor;
            ${Qj}
        `,this._shaderPatch="diffuseColor = Vignette(diffuseColor);",this.enabled=e}get bgcolor(){return console.warn("VignettePlugin.bgcolor is deprecated, use VignettePlugin.color instead"),this.color}set bgcolor(e){console.warn("VignettePlugin.bgcolor is deprecated, use VignettePlugin.color instead"),this.color=e}},f.VignettePlugin.PluginType="Vignette",Bg([de(f.VignettePlugin.prototype.setDirty),ae("Enable"),z()],f.VignettePlugin.prototype,"enabled",2),Bg([Oe("Power",[.1,4],.01),va({propKey:"power"}),z()],f.VignettePlugin.prototype,"power",2),Bg([Tn("Color",r=>({onChange:()=>r?.setDirty()})),va({propKey:"bgcolor"}),z("bgcolor")],f.VignettePlugin.prototype,"color",2),f.VignettePlugin=Bg([gt("Vignette")],f.VignettePlugin);const qj="vec4 ChromaticAberration(in vec4 color){vec2 distFromCenter=vUv-0.5;vec2 aberrated=aberrationIntensity*pow(abs(distFromCenter),vec2(2.0));vec4 outColor=vec4(tDiffuseTexelToLinear(texture2D(tDiffuse,vUv+aberrated)).r,color.g,tDiffuseTexelToLinear(texture2D(tDiffuse,vUv-aberrated)).b,color.a);return outColor;}";var Xj=Object.defineProperty,Yj=Object.getOwnPropertyDescriptor,O_=(r,e,t,i)=>{for(var n=i>1?void 0:i?Yj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Xj(e,t,n),n};f.ChromaticAberrationPlugin=class extends Gd{constructor(e=!0){super(),this.extraUniforms={aberrationIntensity:{value:1}},this.intensity=.5,this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float aberrationIntensity;
            ${qj}
        `,this._shaderPatch="diffuseColor = ChromaticAberration(diffuseColor);",this.enabled=e}get aberrationIntensity(){return console.warn("ChromaticAberrationPlugin.aberrationIntensity is deprecated, use ChromaticAberrationPlugin.intensity instead"),this.intensity}set aberrationIntensity(e){console.warn("ChromaticAberrationPlugin.aberrationIntensity is deprecated, use ChromaticAberrationPlugin.intensity instead"),this.intensity=e}},f.ChromaticAberrationPlugin.PluginType="ChromaticAberration",O_([de(f.ChromaticAberrationPlugin.prototype.setDirty),ae("Enable"),z()],f.ChromaticAberrationPlugin.prototype,"enabled",2),O_([Oe("Intensity",[0,.3],.001),va({propKey:"aberrationIntensity"}),z("aberrationIntensity")],f.ChromaticAberrationPlugin.prototype,"intensity",2),f.ChromaticAberrationPlugin=O_([gt("ChromaticAberration")],f.ChromaticAberrationPlugin);const $j="vec4 FilmicGrain(in vec4 color){float x=(vUv.x+4.0)*(vUv.y+4.0)*(10.0);vec4 grain=vec4(mod((mod(x,13.0)+1.0)*(mod(x,123.0)+1.0),0.01)-0.005)*grainIntensity;return vec4(grainMultiply ?(color.rgb*vec3(1.-grain)):(color.rgb+vec3(grain)),color.a);}";var Kj=Object.defineProperty,Jj=Object.getOwnPropertyDescriptor,Lg=(r,e,t,i)=>{for(var n=i>1?void 0:i?Jj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Kj(e,t,n),n};f.FilmicGrainPlugin=class extends Gd{constructor(e=!0){super(),this.extraUniforms={grainIntensity:{value:1},grainMultiply:{value:!1}},this.intensity=10,this.multiply=!1,this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float grainIntensity;
            uniform bool grainMultiply;
            ${$j}
        `,this._shaderPatch="diffuseColor = FilmicGrain(diffuseColor);",this.enabled=e}get grainIntensity(){return console.warn("FilmicGrainPlugin.grainIntensity is deprecated, use FilmicGrainPlugin.intensity instead"),this.intensity}set grainIntensity(e){console.warn("FilmicGrainPlugin.grainIntensity is deprecated, use FilmicGrainPlugin.intensity instead"),this.intensity=e}},f.FilmicGrainPlugin.PluginType="FilmicGrain",Lg([de(f.FilmicGrainPlugin.prototype.setDirty),ae("Enable"),z()],f.FilmicGrainPlugin.prototype,"enabled",2),Lg([Oe("Intensity",[0,20],.01),va({propKey:"grainIntensity"}),z("grainIntensity")],f.FilmicGrainPlugin.prototype,"intensity",2),Lg([ae("Multiply"),va({propKey:"grainMultiply"}),z("grainMultiply")],f.FilmicGrainPlugin.prototype,"multiply",2),f.FilmicGrainPlugin=Lg([gt("FilmicGrain")],f.FilmicGrainPlugin);var Zj=Object.defineProperty,eW=Object.getOwnPropertyDescriptor,$i=(r,e,t,i)=>{for(var n=i>1?void 0:i?eW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Zj(e,t,n),n};const _i=(Gl=class extends pt{constructor(){super(),this.enabled=!0,this._animations=[],this.autoIncrementTime=!0,this.loopAnimations=!0,this.loopRepetitions=1/0,this.timeScale=1,this.animationSpeed=1,this.animateOnScroll=!1,this.scrollAnimationDamping=.1,this.animateOnPageScroll=!1,this.pageScrollAnimationDamping=.1,this.animateOnDrag=!1,this.dragAxis="y",this.dragAnimationDamping=.3,this.autoplayOnLoad=!1,this.autoplayOnLoadForce=!1,this.syncMaxDuration=!1,this._animationState="none",this._lastAnimationTime=0,this._animationTime=0,this._animationDuration=0,this._scrollAnimationState=0,this._pageScrollAnimationState=0,this._dragAnimationState=0,this._pointerDragHelper=new Fx,this._lastFrameTime=0,this._fadeDisabled=!1,this._lastAnimId="",this.stopOnCheckpointEnd=!0,this.autoUnpauseActions=!0,this.autoEnableActions=!0,this.activeActionWeight=1,this.inactiveActionWeight=0,this._objectAdd=e=>{const t=e.object;if(!this._viewer||!t)return;let i=!1;this._refreshAnimations(t,t)&&(i=!0),i&&(this._onPropertyChange(!this.autoplayOnLoad),(this.autoplayOnLoad||this.autoplayOnLoadForce||this._animationState==="playing")&&this.playAnimation())},this._objectRemove=e=>{const t=e.object;if(!this._viewer||!t)return;const i=this._animations.find(n=>n.object===t);i&&(i.mixer.stopAllAction(),this._animations.splice(this._animations.indexOf(i),1),this.dispatchEvent({type:"removeAnimation",animation:i}))},this._sceneUpdate=e=>{if(!this._viewer)return;this._refreshAnimations(this._viewer.scene.modelRoot,this._viewer.scene.modelRoot)&&(this._onPropertyChange(!this.autoplayOnLoad),(this.autoplayOnLoad||this.autoplayOnLoadForce||this._animationState==="playing")&&this.playAnimation())},this.pageScrollHeight=()=>Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)-window.innerHeight,this.uiConfig={type:"folder",label:"GLTF Animation",children:[...vi(this),()=>this._animations.map(e=>({type:"folder",label:`Animation - ${e.object.name||e.object.uuid}`,children:[...e.actions.map(i=>{const n=i.getClip(),s=i.clipData;return s?{type:"folder",label:`Clip - ${n.name}`,children:[{type:"checkbox",label:"Active",property:[s,"active"]},{type:"input",label:"Name",property:[s,"name"]},{type:"monitor",label:"Duration",getValue:()=>n.duration.toFixed(3)},{type:"number",label:"Start Time",property:[s,"startTime"]},{type:"number",label:"Time Scale",property:[s,"timeScale"]}]}:null})]}))]},this.playClips=this.playClips.bind(this),this.playClip=this.playClip.bind(this),this.playAnimation=this.playAnimation.bind(this),this.playPauseAnimation=this.playPauseAnimation.bind(this),this.pauseAnimation=this.pauseAnimation.bind(this),this.stopAnimation=this.stopAnimation.bind(this),this.resetAnimation=this.resetAnimation.bind(this),this._onPropertyChange=this._onPropertyChange.bind(this),this._postFrame=this._postFrame.bind(this),this._wheel=this._wheel.bind(this),this._scroll=this._scroll.bind(this),this._pointerDragHelper.addEventListener("drag",this._drag.bind(this))}get animations(){return[...this._animations]}get animationState(){return this._animationState}get animationTime(){return this._animationTime}get animationDuration(){return this._animationDuration}playPauseAnimation(){this._animationState==="playing"?this.pauseAnimation():this.playAnimation()}setTime(e){this._animationTime=Math.max(0,Math.min(e,this._animationDuration))}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.scene.addEventListener("sceneUpdate",this._sceneUpdate),e.addEventListener("postFrame",this._postFrame),window.addEventListener("wheel",this._wheel),window.addEventListener("scroll",this._scroll),this._pointerDragHelper.element=e.canvas}onRemove(e){for(;this._animations.length;)this._animations.pop();return e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),e.scene.removeEventListener("sceneUpdate",this._sceneUpdate),e.removeEventListener("postFrame",this._postFrame),window.removeEventListener("wheel",this._wheel),window.removeEventListener("scroll",this._scroll),this._pointerDragHelper.element=void 0,super.onRemove(e)}onStateChange(){this.uiConfig?.uiRefresh?.(!0,"postFrame")}async playClip(e,t=!1){return this.playClips([e],t)}async playClips(e,t=!1){const i=[];return this._animations.forEach(({actions:n})=>{n.forEach(s=>{e.includes(s.getClip().name)&&i.push(s)})}),this.playAnimation(t,i)}async playAnimation(e=!1,t){if(this.isDisabled())return;let i=!1;this._animationState==="playing"&&(this.stopAnimation(!1),i=!0);let n=0;const s=!t;t||(t=[],this._animations.forEach(({actions:o})=>{t.push(...o)})),i?this.resetAnimation():this.animationState!=="paused"&&(t.forEach(o=>{o.reset()}),this._animationTime=0);const a=Ui();this._lastAnimId=a;for(const o of t)o.setLoop(this.loopAnimations?_A:vA,this.loopRepetitions),o.play(),n=Math.max(n,o.getClip().duration/Math.abs(o.timeScale));if(this._animationState="playing",this._viewer?.setDirty(),s){if(!isFinite(this._animationDuration))return;await new Promise(o=>{const l=()=>{this.removeEventListener("checkpointEnd",l),o()};this.addEventListener("checkpointEnd",l)})}else{const o=this.loopAnimations?this.loopRepetitions:1;if(n*=o,!isFinite(n))return;await new Promise(l=>{const c=h=>{h.time>=n&&(this.removeEventListener("animationStep",c),l())};this.addEventListener("animationStep",c)})}a===this._lastAnimId&&this.stopOnCheckpointEnd&&this.stopAnimation(e)}pauseAnimation(){if(this._animationState!=="playing"){console.warn("pauseAnimation called when animation was not playing.");return}this._animationState="paused",this._viewer?.setDirty()}resumeAnimation(){if(this._animationState!=="paused"){console.warn("resumeAnimation called when animation was not paused.");return}this._animationState="playing",this._viewer?.setDirty()}stopAnimation(e=!1){this._animationState="stopped",e?this.resetAnimation():this._viewer?.setDirty(),this._lastAnimId="",this._viewer&&this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1)}resetAnimation(){if(this._animationState!=="stopped"&&this._animationState!=="none"){this.stopAnimation(!0);return}this._animations.forEach(({mixer:e})=>{e.stopAllAction(),e.setTime(0)}),this._animationTime=0,this._viewer?.setDirty()}_postFrame(){if(!this._viewer)return;const e=this.animateOnScroll,t=this.animateOnPageScroll,i=this.animateOnDrag;if(this.isDisabled()||this._animations.length<1||this._animationState!=="playing"){this._lastFrameTime=0,this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1);return}const n=this._animationTime;if(this.autoIncrementTime||t||e||i){const o=Mn()/1e3;this._lastFrameTime<1&&(this._lastFrameTime=o-1/30);let l=o-this._lastFrameTime;l*=this.animationSpeed,this._lastFrameTime=o,t?l*=this._pageScrollAnimationState:e&&i?l*=hS(this._scrollAnimationState,this._dragAnimationState):e?l*=this._scrollAnimationState:i&&(l*=this._dragAnimationState);const c=this._viewer.getPlugin("Progressive")?.postFrameConvergedRecordingDelta();c&&c>0&&(l=c),c===0&&(l=0);const h=Math.abs(this.timeScale);this._animationTime+=l*(h>0?h:1)}else{const o=Mn()/1e3;this._lastFrameTime=o;const l=Math.abs(this.timeScale)*this.animationSpeed;this._animationTime=this._viewer.timeline.time*(l>0?l:1)}const s=this._animationTime-this._lastAnimationTime;if(this._lastAnimationTime=this._animationTime,Math.abs(s)<1e-4)return;n<1e-4&&this.dispatchEvent({type:"checkpointBegin"});const a=this.timeScale<0?(isFinite(this._animationDuration)?this._animationDuration:0)-this._animationTime:this._animationTime;if(this._animations.map(o=>{o.actions.forEach(l=>{const c=l.clipData?.startTime||0,h=l.clipData?.active??!0;l.clipData?.timeScale!==void 0&&(l.timeScale=l.clipData.timeScale),(c!==void 0&&l._startTime===null||l._startTime!==c)&&(l._startTime=c);let u=l.getClip().duration;this.autoIncrementTime&&this.loopAnimations&&(u*=this.loopRepetitions);const d=h&&a>=c&&(!isFinite(u)||a<u/Math.abs(l.timeScale)+c);this.autoUnpauseActions&&l.paused&&d&&(l.paused=!1),this.autoEnableActions&&!l.enabled&&d&&(l.enabled=!0),this.inactiveActionWeight!==null&&!d&&l.weight?l.setEffectiveWeight(this.inactiveActionWeight):this.activeActionWeight!==null&&d&&!l.weight&&l.setEffectiveWeight(this.activeActionWeight)}),o.mixer.setTime(a)}),this._pageScrollAnimationState=this.pageScrollTime-this._animationTime,Math.abs(this._pageScrollAnimationState)<.001?this._pageScrollAnimationState=0:this._pageScrollAnimationState*=1-this.pageScrollAnimationDamping,Math.abs(this._scrollAnimationState)<.001?this._scrollAnimationState=0:this._scrollAnimationState*=1-this.scrollAnimationDamping,Math.abs(this._dragAnimationState)<.001?this._dragAnimationState=0:this._dragAnimationState*=1-this.dragAnimationDamping,this.dispatchEvent({type:"animationStep",delta:s,time:a}),this._viewer.renderManager.resetShadows(),this._viewer.setDirty(),!this._fadeDisabled){const o=this._viewer.getPlugin("FrameFade");o&&(o.disable(Gl.PluginType),this._fadeDisabled=!0)}this._animationTime>=this._animationDuration&&this.dispatchEvent({type:"checkpointEnd"})}_refreshAnimations(e,t){if(!this._viewer)return!1;const i=e.animations;if(i.length<1)return!1;let n=this._animations.find(a=>a.object===e);n=n||{object:e,mixer:new Sx(t),clips:[],actions:[],duration:0},n.clips=i,n.duration=Math.max(...i.map(a=>a.duration)),(t.userData.gltfAnim_SyncMaxDuration??this.syncMaxDuration)&&(i.forEach(a=>a.duration=n.duration),t.userData.gltfAnim_SyncMaxDuration=!0);const s=i.flatMap(a=>{a.userData.clipActions||(a.userData.clipActions={});const o=a.userData.clipActions?.[e.uuid];if(o&&o.length){const c=[];for(const h of o){const u=n.actions.find(d=>d.clipData?.uid===h.uid);u&&c.push(u)}if(c.length)return c}o||(a.userData.clipActions[e.uuid]=[]);const l=n.mixer.clipAction(a);return l.clipData={uid:Ui(),active:!0,name:a.name,startTime:0,timeScale:1},l.setLoop(this.loopAnimations?_A:vA,this.loopRepetitions),a.userData.clipActions[e.uuid].push(l.clipData),l});return n.actions=s,n.actions.forEach(a=>a.clampWhenFinished=!0),this._animations.push(n),this.uiConfig?.uiRefresh?.(!0,"postFrame"),this.dispatchEvent({type:"addAnimation",animation:n}),!0}_onPropertyChange(e=!0){this._animationDuration=Math.max(...this._animations.map(({duration:t})=>t))*(this.loopAnimations?this.loopRepetitions:1),this._animationState==="playing"&&e!==!1&&this.playAnimation()}get pageScrollTime(){const e=this.pageScrollHeight();return window.scrollY/e*(this.animationDuration-.05)}_scroll(){this.isDisabled()||(this._pageScrollAnimationState=this.pageScrollTime-this.animationTime)}_wheel({deltaY:e}){this.isDisabled()||Math.abs(e)>.001&&(this._scrollAnimationState=-1*Math.sign(e))}_drag(e){this.isDisabled()||!this._viewer||(this._dragAnimationState=this.dragAxis==="x"?e.delta.x*this._viewer.canvas.width/4:e.delta.y*this._viewer.canvas.height/4)}},Gl.PluginType="GLTFAnimation",Gl);$i([ei(_i.prototype._onPropertyChange),ae("Loop"),z()],_i.prototype,"loopAnimations",2),$i([ei(_i.prototype._onPropertyChange),z()],_i.prototype,"loopRepetitions",2),$i([Oe("Timescale",[-2,2],.01),z()],_i.prototype,"timeScale",2),$i([Oe("Speed",[.1,4],.1),z()],_i.prototype,"animationSpeed",2),$i([ae(),z()],_i.prototype,"animateOnScroll",2),$i([Oe("Scroll Damping",[0,1]),z()],_i.prototype,"scrollAnimationDamping",2),$i([ae(),z()],_i.prototype,"animateOnPageScroll",2),$i([Oe("Page Scroll Damping",[0,1]),z()],_i.prototype,"pageScrollAnimationDamping",2),$i([ae(),z()],_i.prototype,"animateOnDrag",2),$i([Oi("Drag Axis",[{label:"x"},{label:"y"}]),z()],_i.prototype,"dragAxis",2),$i([Oe("Drag Damping",[0,1]),z()],_i.prototype,"dragAnimationDamping",2),$i([ae(),z()],_i.prototype,"autoplayOnLoad",2),$i([ae("syncMaxDuration(dev)"),z()],_i.prototype,"syncMaxDuration",2),$i([hl()],_i.prototype,"animationState",1),$i([hl()],_i.prototype,"animationTime",1),$i([hl()],_i.prototype,"animationDuration",1),$i([lt("Play/Pause",r=>({label:()=>r.animationState==="playing"?"Pause":"Play"}))],_i.prototype,"playPauseAnimation",1),$i([de(_i.prototype.onStateChange)],_i.prototype,"_animationState",2),$i([ae()],_i.prototype,"autoUnpauseActions",2),$i([ae()],_i.prototype,"autoEnableActions",2),$i([lt("Stop",{sendArgs:!1})],_i.prototype,"stopAnimation",1),$i([lt("Reset",{sendArgs:!1})],_i.prototype,"resetAnimation",1);let tW=_i;const Cr=class Cr extends pt{constructor(){super(),this.toJSON=void 0,this.enabled=!0,this.dependencies=[Vr],this._addSceneObject=e=>{const t=e.object;t?.traverse&&!t.isWidget&&t.traverse(i=>{if(i.isWidget)return;i.userData[Cr.PluginType]?.transforms?.forEach((s,a)=>{s.name===void 0&&(s.name="Transform "+a)});const n={type:"folder",label:"Transform Animation",children:[{type:"button",label:"Add Current Transform",value:()=>{this.addTransform(i),n?.uiRefresh?.()}},()=>i.userData[Cr.PluginType]?.transforms.map((s,a)=>({type:"folder",label:s.name||`Transform ${a}`,children:[{type:"input",label:"Name",property:[s,"name"]},{type:"vec3",label:"Position",property:[s,"position"]},{type:"vec3",label:"Quaternion",property:[s,"quaternion"]},{type:"vec3",label:"Scale",property:[s,"scale"]},{type:"button",label:"Set",value:()=>{this.setTransform(i,s)}},{type:"button",label:"Animate",value:()=>{this.animateTransform(i,s)}}]}))]};i.uiConfig?.children?.push(n)})}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._addSceneObject)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._addSceneObject),super.onRemove(e)}addTransform(e,t){e.userData[Cr.PluginType]||(e.userData[Cr.PluginType]={transforms:[]});const i={name:t||"Transform "+(e.userData[Cr.PluginType].transforms.length+1),position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()};return e.userData[Cr.PluginType].transforms.push(i),i}setTransform(e,t){const i=this.getSavedTransform(t,e);i&&(e.position.copy(i.position),e.quaternion.copy(i.quaternion),e.scale.copy(i.scale),e.setDirty?.(),e.uiConfig?.uiRefresh?.())}getSavedTransform(e,t){return typeof e=="number"?t.userData[Cr.PluginType]?.transforms[e]:typeof e=="string"?t.userData[Cr.PluginType]?.transforms.find(i=>i.name===e):e}animateTransform(e,t,i=2e3){const n=this._viewer?.getPlugin(Vr);n||this._viewer?.console.error("PopmotionPlugin required for animation");const s=this.getSavedTransform(t,e);if(!s)return;const a=new x,o=new Qe,l=new x,c=e.position.clone(),h=e.quaternion.clone(),u=e.scale.clone(),d=s.position,p=s.quaternion,m=s.scale;return n?.animate({from:0,to:1,duration:i,onUpdate:A=>{a.lerpVectors(c,d,A),o.slerpQuaternions(h,p,A),l.lerpVectors(u,m,A),e.position.copy(a),e.quaternion.copy(o),e.scale.copy(l),this._viewer?.setDirty(),this._viewer?.renderManager.resetShadows()},onStop:()=>{e.position.copy(s.position),e.quaternion.copy(s.quaternion),e.scale.copy(s.scale),e.setDirty?.(),e.uiConfig?.uiRefresh?.()}})}};Cr.PluginType="TransformAnimationPlugin";let U_=Cr;var iW=Object.defineProperty,nW=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&iW(e,t,n),n};const GI=(Oa=class extends pt{constructor(){super(),this.enabled=!0,this.dependencies=[Vr],this.animation=new f.AnimationObject(()=>this._viewer,()=>this._viewer,"Viewer Animation"),this.runtimeAnimation=new f.AnimationObject(void 0,()=>this._viewer,"Runtime Animation"),this._fAnimationAdd=e=>{this.rebuildTimeline(),this.dispatchEvent({...e,type:"animationAdd"})},this._fAnimationRemove=e=>{if(this.rebuildTimeline(),this.dispatchEvent(e),e.fromChild&&e.target===this.runtimeAnimation){const t=e.animation.target;t?.userData?.animationObjects&&this._removeAnimationFromObject(e.animation,t);const i=this._visibleBtns.get(e.animation);i&&i.forEach(n=>this._refreshTriggerBtn(e.animation,n))}else this._visibleBtns.delete(e.animation)},this._fAnimationUpdate=e=>{if(this.rebuildTimeline(),this.dispatchEvent({...e,type:"animationUpdate",animation:e.target}),!this._triggerButtonsShown)return;const t=this._visibleBtns.get(e.target);t&&t.forEach(i=>this._refreshTriggerBtn(e.target,i))},this._viewerTimelineUpdate=()=>{!this._viewer||!this._triggerButtonsShown||this._visibleBtns.forEach((e,t)=>{e.forEach(i=>this._refreshTriggerBtn(t,i))})},this._refreshTriggerBtn=(e,t)=>{const i=this._getActiveIndex(e);t.classList.remove("anim-object-uic-trigger-equals"),t.classList.remove("anim-object-uic-trigger-active"),t.dataset.activeIndex=i,i.length&&(t.classList.add("anim-object-uic-trigger-active"),e.isValueSame(parseInt(i))&&t.classList.add("anim-object-uic-trigger-equals"))},this._triggerButtonsShown=!1,this._currentTimeline=[],this._refTimeline=!1,this._viewerListeners={postFrame:()=>{const e=this._viewer?.getPlugin(Vr);this._refTimeline&&e&&(this._refTimeline=!1,this._currentTimeline.forEach(([t,i])=>i.stop()),this._currentTimeline=this.getAllAnimations().map(t=>[t,e.animateObject(t,0,!1,e.timelineDriver)]),this.dispatchEvent({type:"rebuildTimeline",timeline:this._currentTimeline}))}},this._objectAdd=e=>{const t=e.object;t&&(t.isWidget||(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._addAnimationObject(i,t)),this._setupUiConfig(t)))},this._objectRemove=e=>{const t=e.object;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._removeAnimationObject(i)),this._cleanUpUiConfig(t))},this._materialAdd=e=>{const t=e.material;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._addAnimationObject(i,t)),this._setupUiConfig(t))},this._materialRemove=e=>{const t=e.material;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._removeAnimationObject(i)),this._cleanUpUiConfig(t))},this._visibleBtns=new Map,this._iObservers=new WeakMap,this._objectUpdate=e=>{const t=e.object||e.material;if(this.isDisabled()||!this._triggerButtonsShown||!t||t!==e.target)return;const i=e.change||e.key;if(!t.assetType||t.assetType==="widget"||!i)return;const n=this._iObservers.get(t)?.filter(s=>(s.key===i||s.key?.endsWith("."+i))&&s.btn?.parentElement);if(n?.length)for(const s of n){const a=Og(t,s.key);if(!a)return;this._refreshTriggerBtn(a,s.btn)}},this.uiConfig={label:"Viewer Animations",type:"folder",children:[vi(this.animation).filter(e=>{const t=it(e?.label)??"";return["Animate","Stop","Animate Reverse"].includes(t)})??[],()=>vi(this.animation.animSet).map(t=>it(t)).filter(Boolean),{type:"checkbox",label:"Run in Parallel",property:[this.animation,"animSetParallel"]},{type:"button",label:"Add Animation",value:()=>{this.animation.addAnimation(),this.uiConfig.uiRefresh?.(!0,"postFrame",1)}},{type:"checkbox",label:"Show Triggers",property:[this,"triggerButtonsShown"]}]},this.animation.animSetParallel=!0,this.animation.uiConfig.uiRefresh=(...e)=>this.uiConfig.uiRefresh?.(...e),this.animation.addEventListener("animationAdd",this._fAnimationAdd),this.animation.addEventListener("animationRemove",this._fAnimationRemove),this.animation.addEventListener("update",this._fAnimationUpdate),this.runtimeAnimation.animSetParallel=!0,this.runtimeAnimation.uiConfig.uiRefresh=(...e)=>this.uiConfig.uiRefresh?.(...e),this.runtimeAnimation.addEventListener("animationAdd",this._fAnimationAdd),this.runtimeAnimation.addEventListener("animationRemove",this._fAnimationRemove),this.runtimeAnimation.addEventListener("update",this._fAnimationUpdate),this._fAnimationAdd({animation:this.animation}),ll(`
        .anim-object-uic-trigger{
            padding: 4px;
            margin-top: -4px;
            cursor: pointer;
            color: var(--tp-label-foreground-color, #777);
            display: none;
        }
        .anim-object-uic-trigger-visible{
        }
        .anim-object-uic-trigger-active{
            color: blue;
        }
        .anim-object-uic-trigger-equals{
            color: red !important;
        }
        .aouic-triggers-visible .anim-object-uic-trigger{
            display: inline-block;
        }
        `)}getAllAnimations(){return[...this.animation.animSet,...this.runtimeAnimation.animSet]}_getActiveIndex(e){if(!e.target)return"";const i=(1e3*(this._viewer?.timeline.time||0)-e.delay)/e.duration,n=e.offsets,s=n.reduce((l,c,h)=>Math.abs(c-i)<Math.abs(n[l]-i)?h:l,0);return Math.abs(n[s]-i)*e.duration<50?s.toString():""}get triggerButtonsShown(){return this._triggerButtonsShown}set triggerButtonsShown(e){const t=this._triggerButtonsShown!==e;this._triggerButtonsShown=e,e?document.body.classList.add("aouic-triggers-visible"):document.body.classList.remove("aouic-triggers-visible"),t&&e&&this._visibleBtns.forEach((i,n)=>{i.forEach(s=>this._refreshTriggerBtn(n,s))})}showTriggers(e=!0){this.triggerButtonsShown=e}rebuildTimeline(){this._refTimeline=!0}getTimeline(){return this._currentTimeline}addAnimation(e,t,i){return i=i||new f.AnimationObject,e!==void 0&&(i.access=e),t?.userData?(t.userData.animationObjects||(t.userData.animationObjects=[]),t.userData.animationObjects.includes(i)||(t.userData.animationObjects.push(i),this._addAnimationObject(i,t),this._setupUiConfig(t))):this.animation.animSet.includes(i)||this.animation.add(i),i}removeAnimation(e,t){t?.userData?(this._removeAnimationFromObject(e,t),this._removeAnimationObject(e),this._cleanUpUiConfig(t)):this.animation.remove(e)}_addAnimationObject(e,t){e.target=t,this.runtimeAnimation.add(e)}_removeAnimationObject(e){this.runtimeAnimation.remove(e),e.target=void 0}_removeAnimationFromObject(e,t){if(e.target=void 0,!t.userData.animationObjects)return;const i=t.userData.animationObjects.indexOf(e);i>=0&&(t.userData.animationObjects.splice(i,1),t.userData.animationObjects.length<1&&delete t.userData.animationObjects)}_setupUiConfig(e){!(e.isObject3D||e.isMaterial)||!e.uiConfig||e.uiConfig?.children?.find(n=>typeof n=="object"&&n.tags?.includes(Oa.PluginType))||(e.uiConfig?.children?.push({type:"folder",label:"Property Animations",tags:["animation",Oa.PluginType],children:[()=>e.userData.animationObjects?.map(n=>n.uiConfig)]}),this._setupUiConfigButtons(e),e.isObject3D&&e.addEventListener("objectUpdate",this._objectUpdate),e.isMaterial&&e.addEventListener("materialUpdate",this._objectUpdate))}_cleanUpUiConfig(e){this._cleanupUiConfigButtons(e);const t=this._iObservers.get(e);if(t&&(t.forEach(({o:n,btn:s})=>{n.disconnect(),s.remove()}),this._iObservers.delete(e)),e.isObject3D&&e.removeEventListener("objectUpdate",this._objectUpdate),e.isMaterial&&e.removeEventListener("materialUpdate",this._objectUpdate),!e.uiConfig)return;const i=e.uiConfig?.children?.findIndex(n=>typeof n=="object"&&n.tags?.includes(Oa.PluginType));i!==void 0&&i>=0&&e.uiConfig.children?.splice(i,1)}_setupUiConfigButtons(e){const t=this._animatableUiConfigs(e);for(const i of t)this.setupUiConfigButton(e,i)}_cleanupUiConfigButtons(e,t){const i=t??this._animatableUiConfigs(e);for(const n of i)this.cleanupUiConfigButton(n)}setupUiConfigButton(e,t,i){if(t._animTriggerInit)return;const n=it(t.property);if(!n)return;const[s,a]=n;if(!s||typeof a!="string"||s!==e&&!i)return;const o=i?i.endsWith(".")?i+a:i:a,l=Pr({innerHTML:"◆",classList:["anim-object-uic-trigger"],addToBody:!1});l.parentElement&&l.remove(),l.dataset.isAnimObjectTrigger="1",l.title="Add Animation for "+it(t.label,a),l.addEventListener("click",()=>{const u=this._viewer?.getPlugin("UndoManagerPlugin");let d=Og(e,o);const p=1e3*(this._viewer?.timeline.time||0);if(d){if(d.values.length>1){const m=d,A=l.dataset.activeIndex||"",g=this._getActiveIndex(d);if(g===A){const y=parseInt(g||"-1"),_=()=>this._refreshTriggerBtn(m,l);u?(y<0?u.performAction(d,d.addKeyframe,[p],"addKeyframe-"+d.access,_):u.performAction(d,d.updateKeyframe,[y],"editKeyframe-"+d.access,_),_()):(y<0?d.addKeyframe(p):d.updateKeyframe(y),_())}else console.error("Active index mismatch",g,A)}}else{d=new f.AnimationObject,d.access=o,d.name=e.name+" "+(it(t.label,o)||o),d.updateTarget=!0,d.delay=p,d.duration=2e3;const m=d,A={redo:()=>{e.userData.animationObjects||(e.userData.animationObjects=[]),e.userData.animationObjects.push(m),this._addAnimationObject(m,e),this._refreshTriggerBtn(m,l)},undo:()=>{m.removeFromParent(),this._refreshTriggerBtn(m,l)}};A.redo(),u?.undoManager?.record(A)}this._setBtnVisible(d,l,!0)});const c=new IntersectionObserver(u=>{const d=Og(e,o);if(d)for(const p of u)p.target===l&&this._setBtnVisible(d,l,p.isIntersecting)});c.observe(l),this._iObservers.has(e)||this._iObservers.set(e,[]),this._iObservers.get(e)?.push({o:c,btn:l,key:o});const h=Og(e,o);h&&this._refreshTriggerBtn(h,l),t._animTriggerInit=!0,t.domChildren=!t.domChildren||Array.isArray(t.domChildren)?[...t.domChildren||[],l]:t.domChildren}cleanupUiConfigButton(e){e&&(e.domChildren=Array.isArray(e.domChildren)?e.domChildren?.filter(t=>!(t instanceof HTMLElement&&t.dataset.isAnimObjectTrigger))||[]:e.domChildren)}_setBtnVisible(e,t,i){this._visibleBtns.has(e)||this._visibleBtns.set(e,new Set);const n=this._visibleBtns.get(e);i?n.has(t)||(t.classList.add("anim-object-uic-trigger-visible"),n.add(t)):(t.classList.remove("anim-object-uic-trigger-visible"),n.delete(t))}_animatableUiConfigs(e){return e.uiConfig?.children?.filter(t=>typeof t=="object"&&t.type&&["vec3","color","number","checkbox","toggle","slider"].includes(t.type)&&Array.isArray(t.property)&&t.property[0]===e&&(!e.constructor?.InterpolateProperties||e.constructor.InterpolateProperties.includes(t.property[1])))||[]}onAdded(e){super.onAdded(e),e.timeline.addEventListener("update",this._viewerTimelineUpdate),e._animGetters={objects:(t,i)=>{if(!e)return;const n=e.object3dManager.findObject(t);return{tar:n,acc:i,onChange:n?()=>{n.setDirty&&n.setDirty({refreshScene:!1,frameFade:!1})}:void 0}},materials:(t,i)=>{if(!e)return;const n=e.object3dManager.findMaterial(t);return{tar:n,acc:i,onChange:n?()=>{n.setDirty&&n.setDirty({frameFade:!1})}:void 0}}},this._setupUiConfig(e.scene),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.object3dManager.getMaterials().forEach(t=>this._materialAdd({material:t})),e.object3dManager.addEventListener("materialAdd",this._materialAdd),e.object3dManager.addEventListener("materialRemove",this._materialRemove)}onRemove(e){this._cleanUpUiConfig(e.scene),e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),e.object3dManager.removeEventListener("materialAdd",this._materialAdd),e.object3dManager.removeEventListener("materialRemove",this._materialRemove),e.object3dManager.getMaterials().forEach(t=>this._materialRemove({material:t})),delete e._animGetters,super.onRemove(e)}fromJSON(e,t){return super.fromJSON(e,t)?this:null}},Oa.PluginType="AnimationObjectPlugin",Oa);nW([z()],GI.prototype,"animation");let sW=GI;const Og=(r,e)=>r?.userData.animationObjects?.find(t=>t.access===e);var rW=Object.defineProperty,aW=Object.getOwnPropertyDescriptor,zI=(r,e,t,i)=>{for(var n=i>1?void 0:i?aW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&rW(e,t,n),n};f.ClearcoatTintPlugin=class extends pt{constructor(){super(),this.enabled=!0,this._uniforms={ccTintColor:{value:new se},ccThickness:{value:0},ccIor:{value:0}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._clearcoatTint?.enableTint||!(t.clearcoat>0)?"":ma`
uniform vec3 ccTintColor;
uniform float ccThickness;
uniform float ccIor;
vec3 clearcoatTint(const in float dotNV, const in float dotNL, const in float clearcoat) {
    vec3 tint = ( ccThickness > 0. ? 1. - ccTintColor : ccTintColor); // Set thickness < 0 for glow.
    tint = exp(tint * -(ccThickness * ((dotNL + dotNV) / max(dotNL * dotNV, 1e-3)))); // beer's law
    return mix(vec3(1.0), tint, clearcoat);
}
        `,shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._clearcoatTint?.enableTint||!(t.clearcoat>0)||(e.fragmentShader=At(e.fragmentShader,"float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );","float dotNVcc = saturate( dot( geometryClearcoatNormal, -refract(geometryViewDir, geometryClearcoatNormal, 1./ccIor) ) );"),e.fragmentShader=At(e.fragmentShader,"outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;",`outgoingLight *= clearcoatTint(dotNVcc, dotNVcc, material.clearcoat);
`,{prepend:!0}),e.defines&&(e.defines.USE_UV=""))},onObjectRender:(e,t)=>{const i=t.userData._clearcoatTint;i?.enableTint&&(this._uniforms.ccTintColor.value.set(i.tintColor),this._uniforms.ccThickness.value=i.thickness,this._uniforms.ccIor.value=i.ior,ba({CLEARCOAT_TINT_ENABLED:+!this.isDisabled()},t))},extraUniforms:{},computeCacheKey:e=>(this.isDisabled()?"0":"1")+(e.userData._clearcoatTint?.enableTint?"1":"0")+(e.clearcoat>0?"1":"0"),isCompatible:e=>e.isPhysicalMaterial,getUiConfig:e=>{const t=this._viewer;e.userData._clearcoatTint===void 0&&(e.userData._clearcoatTint={});const i=e.userData._clearcoatTint,n={type:"folder",label:"Clearcoat Tint",onChange:s=>{s.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i.enableTint||!1},set value(s){s!==i.enableTint&&(s?f.ClearcoatTintPlugin.AddClearcoatTint(e)||t.dialog.alert("Cannot add clearcoat tint."):(i.enableTint=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"color",label:"Tint color",hidden:()=>!i.enableTint,property:[i,"tintColor"]},{type:"input",label:"Thickness",hidden:()=>!i.enableTint,property:[i,"thickness"]},{type:"slider",bounds:[.8,2.5],label:"IOR",hidden:()=>!i.enableTint,property:[i,"ior"]}]};return n}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}static AddClearcoatTint(e,t){const i=e?.userData;if(!i)return null;i._clearcoatTint||(i._clearcoatTint={});const n=i._clearcoatTint;return n.enableTint=!0,n.tintColor===void 0&&(n.tintColor="#ffffff"),n.thickness===void 0&&(n.thickness=.1),n.ior===void 0&&(n.ior=1.5),t&&Object.assign(n,t),e.setDirty&&e.setDirty(),n}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Sh)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Sh.name),super.onRemove(e)}},f.ClearcoatTintPlugin.PluginType="ClearcoatTintPlugin",f.ClearcoatTintPlugin.CLEARCOAT_TINT_GLTF_EXTENSION="WEBGI_materials_clearcoat_tint",zI([ae("Enabled",r=>({onChange:r.setDirty})),z()],f.ClearcoatTintPlugin.prototype,"enabled",2),f.ClearcoatTintPlugin=zI([gt("Clearcoat Tint (MatExt)")],f.ClearcoatTintPlugin);class oW{constructor(e){this.parser=e,this.name=Sh.name}async extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),f.ClearcoatTintPlugin.AddClearcoatTint(t),ke.Deserialize(s,t.userData._clearcoatTint)}}const Sh={name:"WEBGI_materials_clearcoat_tint",import:r=>new oW(r),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._clearcoatTint?.enableTint)return;t.extensions=t.extensions||{};const i=ke.Serialize(e.userData._clearcoatTint);t.extensions[Sh.name]=i,r.extensionsUsed[Sh.name]=!0}}),textures:void 0},lW=`#include <randomHelpers>
#include <voronoiNoise>
uniform vec2 noiseBumpParams;uniform float noiseBumpScale;uniform float noiseBumpFlakeScale;uniform float noiseFlakeClamp;uniform float noiseFlakeRadius;uniform bool useColorFlakes;uniform vec4 flakeParams;uniform vec3 flakeFallOffParams;vec3 perturbNormalArb_nb(vec3 surf_pos,vec3 surf_norm,vec2 dHdxy,float faceDirection){
#ifdef BUMP_MAP_SCALE_LEGACY
vec3 vSigmaX=(dFdx(surf_pos.xyz));vec3 vSigmaY=(dFdy(surf_pos.xyz));
#else
vec3 vSigmaX=normalize(dFdx(surf_pos.xyz));vec3 vSigmaY=normalize(dFdy(surf_pos.xyz));
#endif
vec3 vN=surf_norm;vec3 R1=cross(vSigmaY,vN);vec3 R2=cross(vN,vSigmaX);float fDet=dot(vSigmaX,R1)*faceDirection;vec3 vGrad=sign(fDet)*(dHdxy.x*R1+dHdxy.y*R2);return normalize(abs(fDet)*surf_norm-vGrad);}`,cW=`vec3 outColor,outColor1,outColor2,outColor3,outColor4,outColor5;float distFac=length(vViewPosition.xyz);/*float e=floor(log2(0.3*distFac+3.0)/0.3785116);float level_z=0.1*pow(1.3,e)-0.2;*/float level=1.;vec2 uvMod=noiseBumpFlakeScale*noiseBumpParams.xy*vUv*level;float voronoiDist=clamp(voronoi_f1_2d(uvMod,1.,noiseFlakeClamp,noiseFlakeRadius,outColor),0.0,1.0);vec3 oldNormal=normal;normal=perturbNormalArb_nb(-vViewPosition,normal,(2.*outColor.xy-1.)*noiseBumpScale,faceDirection);float oldRoughnessFactor=roughnessFactor;float oldMetalnessFactor=metalnessFactor;roughnessFactor=mix(roughnessFactor,flakeParams.x,1.-voronoiDist);metalnessFactor=mix(metalnessFactor,flakeParams.y,1.-voronoiDist);
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
vec3 sparkleRadiance=getIBLRadiance(normalize(vViewPosition),normal,roughnessFactor);float sparkleIntensity=length(sparkleRadiance);float sparkleIntensityMultiplier=sparkleIntensity>1.3 ? flakeParams.z : 1.;vec3 oldDiffuseColor=diffuseColor.rgb;vec2 cellPosition_=floor(uvMod);vec3 colorRGB=useColorFlakes ? hash3(cellPosition_): vec3(1.);float fallOff_=mix(1.,1./(1.+flakeFallOffParams.y*distFac+flakeFallOffParams.z*distFac*distFac),flakeFallOffParams.x);diffuseColor.rgb*=mix(vec3(1.),sparkleIntensityMultiplier*colorRGB*fallOff_,vec3(1.-voronoiDist));if(sparkleIntensity<flakeParams.w){float mixFactor=1.;roughnessFactor=mix(roughnessFactor,oldRoughnessFactor,mixFactor);metalnessFactor=mix(metalnessFactor,oldMetalnessFactor,mixFactor);normal=normalize(mix(normal,oldNormal,mixFactor));diffuseColor.rgb=mix(diffuseColor.rgb,oldDiffuseColor,mixFactor);}
#endif
`;var hW=Object.defineProperty,uW=Object.getOwnPropertyDescriptor,VI=(r,e,t,i)=>{for(var n=i>1?void 0:i?uW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&hW(e,t,n),n};f.NoiseBumpMaterialPlugin=class extends pt{constructor(){super(),this.enabled=!0,this._uniforms={noiseBumpParams:{value:new $},noiseBumpScale:{value:.05},noiseBumpFlakeScale:{value:1e3},noiseFlakeClamp:{value:1},noiseFlakeRadius:{value:.5},flakeParams:{value:new rt(0,1,3,0)},flakeFallOffParams:{value:new x(0,1,0)},useColorFlakes:{value:!1}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._noiseBumpMat?.hasBump?"":lW,shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._noiseBumpMat?.hasBump||(e.fragmentShader=At(e.fragmentShader,"#glMarker beforeAccumulation",cW,{prepend:!0}),e.defines&&(e.defines.USE_UV=""),e.extensionDerivatives=!0)},onObjectRender:(e,t)=>{const i=t.userData._noiseBumpMat;i?.hasBump&&(Array.isArray(i.bumpNoiseParams)?this._uniforms.noiseBumpParams.value.fromArray(i.bumpNoiseParams):this._uniforms.noiseBumpParams.value.copy(i.bumpNoiseParams),this._uniforms.noiseBumpScale.value=i.bumpScale,this._uniforms.noiseBumpFlakeScale.value=i.flakeScale,this._uniforms.noiseFlakeClamp.value=i.flakeClamp,this._uniforms.noiseFlakeRadius.value=i.flakeRadius,Array.isArray(i.flakeParams)?this._uniforms.flakeParams.value.fromArray(i.flakeParams):this._uniforms.flakeParams.value.copy(i.flakeParams),Array.isArray(i.flakeFallOffParams)?this._uniforms.flakeFallOffParams.value.fromArray(i.flakeFallOffParams):this._uniforms.flakeFallOffParams.value.copy(i.flakeFallOffParams),this._uniforms.useColorFlakes.value=i.useColorFlakes,ba({NOISE_BUMP_MATERIAL_ENABLED:+!this.isDisabled()},t))},extraUniforms:{},computeCacheKey:e=>(this.isDisabled()?"0":"1")+(e.userData._noiseBumpMat?.hasBump?"1":"0"),isCompatible:e=>e.isPhysicalMaterial,getUiConfig:e=>{const t=this._viewer;e.userData._noiseBumpMat===void 0&&(e.userData._noiseBumpMat={});const i=e.userData._noiseBumpMat,n={type:"folder",label:"SparkleBump (NoiseBump)",onChange:s=>{s.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i.hasBump||!1},set value(s){s!==i.hasBump&&(s?f.NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(e)||t.dialog.alert("Cannot add NoiseBumpMaterial."):(i.hasBump=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"vec4",label:"Bump Noise Params",bounds:[0,1],hidden:()=>!i.hasBump,property:[i,"bumpNoiseParams"]},{type:"slider",label:"Bump Scale",bounds:[0,.001],stepSize:1e-5,hidden:()=>!i.hasBump,property:[i,"bumpScale"]},{type:"slider",label:"Flake Scale",bounds:[100,1e4],stepSize:1e-4,hidden:()=>!i.hasBump,property:[i,"flakeScale"]},{type:"slider",label:"Flake Clamp",bounds:[0,1],stepSize:1,hidden:()=>!i.hasBump,property:[i,"flakeClamp"]},{type:"slider",label:"Flake Radius",bounds:[.01,1],stepSize:.001,hidden:()=>!i.hasBump,property:[i,"flakeRadius"]},{type:"slider",label:"Flake Roughness",bounds:[0,1],stepSize:.01,hidden:()=>!i.hasBump,property:[i.flakeParams,"x"]},{type:"slider",label:"Flake Metalness",bounds:[0,1],stepSize:.01,hidden:()=>!i.hasBump,property:[i.flakeParams,"y"]},{type:"slider",label:"Flake Strength",bounds:[0,100],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeParams,"z"]},{type:"slider",label:"Flake Threshold",bounds:[.1,10],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeParams,"w"]},{type:"slider",label:"Falloff",stepSize:1,bounds:[0,1],hidden:()=>!i.hasBump,property:[i.flakeFallOffParams,"x"]},{type:"slider",label:"Linear falloff factor",bounds:[0,10],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeFallOffParams,"y"]},{type:"slider",label:"Quadratic falloff factor",bounds:[0,10],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeFallOffParams,"z"]},{type:"checkbox",label:"Colored Flakes",hidden:()=>!i.hasBump,property:[i,"useColorFlakes"]}]};return n}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}static AddNoiseBumpMaterial(e,t){const i=e?.userData;if(!i)return!1;i._noiseBumpMat||(i._noiseBumpMat={});const n=i._noiseBumpMat;return n.hasBump=!0,n.bumpNoiseParams===void 0&&(n.bumpNoiseParams=new $(.5,.5)),n.bumpScale===void 0&&(n.bumpScale=.05),n.flakeScale===void 0&&(n.flakeScale=.05),n.flakeClamp===void 0&&(n.flakeClamp=1),n.flakeRadius===void 0&&(n.flakeRadius=.3),n.useColorFlakes===void 0&&(n.useColorFlakes=!1),n.flakeParams===void 0&&(n.flakeParams=new rt(0,1,3,0)),n.flakeFallOffParams===void 0&&(n.flakeFallOffParams=new x(0,1,0)),t&&Object.assign(n,t),e.setDirty&&e.setDirty(),!0}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Eh)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Eh.name),super.onRemove(e)}},f.NoiseBumpMaterialPlugin.PluginType="NoiseBumpMaterialPlugin",f.NoiseBumpMaterialPlugin.NOISE_BUMP_MATERIAL_GLTF_EXTENSION="WEBGI_materials_noise_bump",VI([ae("Enabled",r=>({onChange:r.setDirty})),z()],f.NoiseBumpMaterialPlugin.prototype,"enabled",2),f.NoiseBumpMaterialPlugin=VI([gt("Noise/Sparkle Bump (MatExt)")],f.NoiseBumpMaterialPlugin);class dW{constructor(e){this.parser=e,this.name=Eh.name}async extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),f.NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(t),ke.Deserialize(s,t.userData._noiseBumpMat)}}const Eh={name:"WEBGI_materials_noise_bump",import:r=>new dW(r),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._noiseBumpMat?.hasBump)return;t.extensions=t.extensions||{};const i=ke.Serialize(e.userData._noiseBumpMat);t.extensions[Eh.name]=i,r.extensionsUsed[Eh.name]=!0}}),textures:void 0},fW=`#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
#if CUSTOM_BUMP_MAP_BICUBIC > 0
vec4 cubic_cb(float v){vec4 n=vec4(1.0,2.0,3.0,4.0)-v;vec4 s=n*n*n;float x=s.x;float y=s.y-4.0*s.x;float z=s.z-4.0*s.y+6.0*s.x;float w=6.0-x-y-z;return vec4(x,y,z,w)*(1.0/6.0);}vec4 textureBicubic_cb(sampler2D sampler,vec2 texCoords){vec2 texSize=vec2(textureSize(sampler,0));vec2 invTexSize=1.0/texSize;texCoords=texCoords*texSize-0.5;vec2 fxy=fract(texCoords);texCoords-=fxy;vec4 xcubic=cubic_cb(fxy.x);vec4 ycubic=cubic_cb(fxy.y);vec4 c=texCoords.xxyy+vec2(-0.5,+1.5).xyxy;vec4 s=vec4(xcubic.xz+xcubic.yw,ycubic.xz+ycubic.yw);vec4 offset=c+vec4(xcubic.yw,ycubic.yw)/s;offset*=invTexSize.xxyy;vec4 sample0=texture(sampler,offset.xz);vec4 sample1=texture(sampler,offset.yz);vec4 sample2=texture(sampler,offset.xw);vec4 sample3=texture(sampler,offset.yw);float sx=s.x/(s.x+s.y);float sy=s.z/(s.z+s.w);return mix(mix(sample3,sample2,sx),mix(sample1,sample0,sx),sy);}
#endif
varying vec2 vCustomBumpUv;uniform sampler2D customBumpMap;uniform float customBumpScale;vec2 dHdxy_fwd_cb(){vec2 dSTdx=dFdx(vCustomBumpUv);vec2 dSTdy=dFdy(vCustomBumpUv);
#if CUSTOM_BUMP_MAP_BICUBIC > 0
float Hll=customBumpScale*textureBicubic_cb(customBumpMap,vCustomBumpUv).x;float dBx=customBumpScale*textureBicubic_cb(customBumpMap,vCustomBumpUv+dSTdx).x-Hll;float dBy=customBumpScale*textureBicubic_cb(customBumpMap,vCustomBumpUv+dSTdy).x-Hll;
#else
float Hll=customBumpScale*texture2D(customBumpMap,vCustomBumpUv).x;float dBx=customBumpScale*texture2D(customBumpMap,vCustomBumpUv+dSTdx).x-Hll;float dBy=customBumpScale*texture2D(customBumpMap,vCustomBumpUv+dSTdy).x-Hll;
#endif
return vec2(dBx,dBy);}
#ifndef USE_BUMPMAP
vec3 perturbNormalArb(vec3 surf_pos,vec3 surf_norm,vec2 dHdxy,float faceDirection){
#ifdef BUMP_MAP_SCALE_LEGACY
vec3 vSigmaX=(dFdx(surf_pos.xyz));vec3 vSigmaY=(dFdy(surf_pos.xyz));
#else
vec3 vSigmaX=normalize(dFdx(surf_pos.xyz));vec3 vSigmaY=normalize(dFdy(surf_pos.xyz));
#endif
vec3 vN=surf_norm;vec3 R1=cross(vSigmaY,vN);vec3 R2=cross(vN,vSigmaX);float fDet=dot(vSigmaX,R1)*faceDirection;vec3 vGrad=sign(fDet)*(dHdxy.x*R1+dHdxy.y*R2);return normalize(abs(fDet)*surf_norm-vGrad);}
#endif
#endif
`;var pW=Object.defineProperty,mW=Object.getOwnPropertyDescriptor,F_=(r,e,t,i)=>{for(var n=i>1?void 0:i?mW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&pW(e,t,n),n};f.CustomBumpMapPlugin=class extends pt{constructor(){super(),this.enabled=!0,this.bicubicFiltering=!0,this._defines={CUSTOM_BUMP_MAP_DEBUG:!1,CUSTOM_BUMP_MAP_BICUBIC:!0},this._uniforms={customBumpUvTransform:{value:new mt},customBumpScale:{value:.001},customBumpMap:{value:null}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._hasCustomBump?"":fW,shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._hasCustomBump||!t.userData._customBumpMap||(e.fragmentShader=At(e.fragmentShader,"#glMarker beforeAccumulation",`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
    normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd_cb(), faceDirection );
#endif
                `,{prepend:!0}),e.vertexShader=At(e.vertexShader,"#include <uv_pars_vertex>",`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
    varying vec2 vCustomBumpUv;
    uniform mat3 customBumpUvTransform;
#endif
                `,{prepend:!0}),e.vertexShader=At(e.vertexShader,"#include <uv_vertex>",`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
    vCustomBumpUv = ( customBumpUvTransform * vec3( uv, 1 ) ).xy;
#endif
                `,{prepend:!0}),e.defines&&(e.defines.USE_UV=""))},onObjectRender:(e,t)=>{const i=t.userData;if(!i?._hasCustomBump||!e.isMesh||!e.geometry)return;const n=i._customBumpMap?.isTexture?i._customBumpMap:null;this._uniforms.customBumpMap.value=n,this._uniforms.customBumpScale.value=n?i._customBumpScale??0:0,n&&(n.updateMatrix(),this._uniforms.customBumpUvTransform.value.copy(n.matrix)),ba({...this._defines,CUSTOM_BUMP_MAP_ENABLED:+this.enabled},t)},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData._hasCustomBump?"1":"0")+e.userData?._customBumpMap?.uuid,isCompatible:e=>e.isPhysicalMaterial,getUiConfig:e=>{const t=this._viewer,i=this.enableCustomBump.bind(this),n=e.userData,s={type:"folder",label:"CustomBumpMap",onChange:a=>{a.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return n._hasCustomBump||!1},set value(a){a!==n._hasCustomBump&&(a?i(e)||t.dialog.alert("CustomBumpMapPlugin - Cannot add CustomBumpMap."):(n._hasCustomBump=!1,e.setDirty&&e.setDirty()),s.uiRefresh?.(!0,"postFrame"))}},{type:"slider",label:"Bump Scale",bounds:[-20,20],stepSize:.001,hidden:()=>!n._hasCustomBump,property:[n,"_customBumpScale"]},{type:"image",label:"Bump Map",hidden:()=>!n._hasCustomBump,property:[n,"_customBumpMap"],onChange:()=>{e.setDirty&&e.setDirty()}},Ti(n,"_customBumpMap","Sampler",()=>!n._hasCustomBump,()=>e.setDirty&&e.setDirty())]};return s}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}enableCustomBump(e,t,i){const n=e?.userData;if(!n)return!1;if(n._hasCustomBump===void 0){const s=e.appliedMeshes;let a=!0;if(s)for(const{geometry:o}of s)o&&(!o.attributes.position||!o.attributes.normal||!o.attributes.uv)&&(a=!1);if(!a)return!1}return n._hasCustomBump=!0,n._customBumpScale=i??n._customBumpScale??.001,n._customBumpMap=t??n._customBumpMap??null,e.setDirty&&e.setDirty(),!0}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Mh)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Mh.name),super.onRemove(e)}},f.CustomBumpMapPlugin.PluginType="CustomBumpMapPlugin",f.CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION="WEBGI_materials_custom_bump_map",F_([ae("Enabled",r=>({onChange:r.setDirty})),z()],f.CustomBumpMapPlugin.prototype,"enabled",2),F_([ae("Bicubic",r=>({onChange:r.setDirty})),hm("CUSTOM_BUMP_MAP_BICUBIC",void 0,!0,f.CustomBumpMapPlugin.prototype.setDirty),z()],f.CustomBumpMapPlugin.prototype,"bicubicFiltering",2),f.CustomBumpMapPlugin=F_([gt("Custom BumpMap (MatExt)")],f.CustomBumpMapPlugin);class gW{constructor(e,t){this._viewer=t,this.parser=e,this.name=Mh.name}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),t.userData._hasCustomBump=!0,t.userData._customBumpScale=s.customBumpScale??0;const a=s.resources?await this._viewer?.loadConfigResources(s.resources):void 0,o=[],l=s.customBumpMap;return l&&(l&&l.resource&&typeof l.resource=="string"?t.userData._customBumpMap=ke.Deserialize(l,null,a,!1):l&&l.index!==void 0?o.push(i.assignTexture(t.userData,"_customBumpMap",l).then(c=>{c.colorSpace=vt})):(console.warn("CustomBumpMapPlugin: Invalid Texture Map in extension",l,n.name),t.userData._customBumpMap=null)),Promise.all(o)}}const Mh={name:"WEBGI_materials_custom_bump_map",import:(r,e)=>new gW(r,e),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._hasCustomBump||(e.userData._customBumpScale||0)<.001)return;t.extensions=t.extensions||{};const i={images:{},textures:{}},n={};n.customBumpScale=e.userData._customBumpScale||1;const s=e.userData._customBumpMap?.userData.rootPath;if(s&&Hc(s)&&(n.customBumpMap=ke.Serialize(e.userData._customBumpMap,i,!1)),r.checkEmptyMap(e.userData._customBumpMap)&&n.customBumpMap===void 0){const a={index:r.processTexture(e.userData._customBumpMap)};r.applyTextureTransform(a,e.userData._customBumpMap),n.customBumpMap=a}(Object.keys(i.textures).length||Object.keys(i.images).length)&&(n.resources=i),t.extensions[Mh.name]=n,r.extensionsUsed[Mh.name]=!0}}),textures:{customBumpMap:"RGB"}},AW=`
#ifdef USE_BUMPMAP
mat3 mat3_inverse(mat3 A){mat3 M_t=mat3(vec3(A[0][0],A[1][0],A[2][0]),vec3(A[0][1],A[1][1],A[2][1]),vec3(A[0][2],A[1][2],A[2][2]));float det=dot(cross(M_t[0],M_t[1]),M_t[2]);mat3 adjugate=mat3(cross(M_t[1],M_t[2]),cross(M_t[2],M_t[0]),cross(M_t[0],M_t[1]));return adjugate/det;}float CalculateHeight(in vec2 texCoords){float height=texture2D(bumpMap,texCoords).x;return clamp(height,0.0,1.0);}const vec2 bumpMapSize=vec2(512,512);vec3 CalculateNormal(in vec2 texCoords){
#if defined( TANGENTSPACE_NORMALMAP ) && 0
vec3 mapN=texture2D(normalMap,texCoords).xyz;mapN.xy*=normalScale;return normalize(mapN);
#else
vec2 texOffs=1.0/bumpMapSize;
#if PARALLAX_NORMAL_MAP_QUALITY > 0
float hx[9];hx[0]=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,-1.0)).r;hx[1]=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,-1.0)).r;hx[2]=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,-1.0)).r;hx[3]=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,0.0)).r;hx[4]=texture2D(bumpMap,texCoords.st).r;hx[5]=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,0.0)).r;hx[6]=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,1.0)).r;hx[7]=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,1.0)).r;hx[8]=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,1.0)).r;vec2 deltaH=vec2(hx[0]-hx[2]+2.0*(hx[3]-hx[5])+hx[6]-hx[8],hx[0]-hx[6]+2.0*(hx[1]-hx[7])+hx[2]-hx[8]);
#else
float h_xa=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,0.0)).r;float h_xb=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,0.0)).r;float h_ya=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,-1.0)).r;float h_yb=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,1.0)).r;vec2 deltaH=vec2(h_xa-h_xb,h_ya-h_yb);
#endif
return normalize(vec3(deltaH/texOffs,1.0));
#endif
}vec3 ReliefParallax(in float frontFace,in vec3 texDir3D,in vec2 texCoord){float surf_sign=frontFace;float back_face=step(0.0,-surf_sign);vec2 texStep=surf_sign*texDir3D.xy/abs(texDir3D.z);vec2 texC=texCoord.st+surf_sign*texStep+back_face*texStep.xy;float mapHeight=1.0;float bumpHeightStep=1.0/float(PARALLAX_MAP_STEPS);float bestBumpHeight=mapHeight+bumpHeightStep;
#pragma unroll_loop_start
for(int i=0;i<PARALLAX_MAP_STEPS;i++){if(mapHeight<bestBumpHeight){bestBumpHeight-=bumpHeightStep;mapHeight=back_face+surf_sign*CalculateHeight(texC.xy-bestBumpHeight*texStep.xy);}}
#pragma unroll_loop_end
bestBumpHeight+=bumpHeightStep;
#pragma unroll_loop_start
for(int i=0;i<PARALLAX_MAP_B_STEPS;i++){bumpHeightStep*=0.5;bestBumpHeight-=bumpHeightStep;mapHeight=back_face+surf_sign*CalculateHeight(texC.xy-bestBumpHeight*texStep.xy);bestBumpHeight+=(bestBumpHeight<mapHeight)? bumpHeightStep : 0.0;}
#pragma unroll_loop_end
bestBumpHeight-=bumpHeightStep*clamp((bestBumpHeight-mapHeight)/bumpHeightStep,0.0,1.0);mapHeight=bestBumpHeight;texC-=mapHeight*texStep;return vec3(texC.xy,mapHeight);}vec3 reliefParallaxPerturbNormal(in float faceDirection,inout vec3 normal){if(abs(bumpScale)<0.001)return vec3(vBumpMapUv,0.);float parallaxHeight;vec2 texCoords=vBumpMapUv;float face_sign=sign(dot(normal,vViewPosition));vec3 N=normalize(normal);vec3 dp1=dFdx(-vViewPosition);vec3 dp2=dFdy(-vViewPosition);vec2 duv1=dFdx(vBumpMapUv);vec2 duv2=dFdy(vBumpMapUv);vec3 dp2perp=cross(dp2,N);vec3 dp1perp=cross(N,dp1);vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(T,T),dot(B,B)));mat3 tbnMat=mat3(T*invmax,B*invmax,N*bumpScale);vec3 tangentPos=normalize(mat3_inverse(tbnMat)*-vViewPosition);vec3 parallaxUv=ReliefParallax(face_sign,tangentPos,vBumpMapUv);tbnMat[2]=face_sign*N/bumpScale;normal=normalize(tbnMat*CalculateNormal(parallaxUv.xy).xyz);
#ifdef FLIP_SIDED
normal=-normal;
#endif
return parallaxUv;}
#endif
`;var yW=Object.defineProperty,vW=Object.getOwnPropertyDescriptor,Th=(r,e,t,i)=>{for(var n=i>1?void 0:i?vW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&yW(e,t,n),n};f.ParallaxMappingPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.stepCount=12,this.binaryStepCount=3,this.debugNormals=!1,this.debugHitHeight=!1,this._defines={PARALLAX_NORMAL_MAP_QUALITY:0},this._bumpMapExtension={shaderExtender:(t,i,n)=>{if(!(!i.bumpMap||this.isDisabled())){t.fragmentShader=t.fragmentShader.replace("#include <normal_fragment_begin>",""),t.fragmentShader=t.fragmentShader.replace("#include <normal_fragment_maps>",""),t.fragmentShader=t.fragmentShader.replace("#include <map_fragment>",`#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <map_fragment>`);for(const s of["map_fragment","alphamap_fragment","roughnessmap_fragment","metalnessmap_fragment","emissivemap_fragment","transmission_fragment"])t.fragmentShader=At(t.fragmentShader,`#include <${s}>`,ot[s].replace(/\bv\w+Uv\b/g,"parallaxUv.xy",{replaceAll:!0}));(this.debugNormals||this.debugHitHeight)&&(t.fragmentShader=At(t.fragmentShader,"texture2D( map, parallaxUv.xy )",this.debugNormals?"vec4(normal, 1.); normal = nonPerturbedNormal":"vec4(parallaxUv.z,0., 0., 1.)")),t.fragmentShader=At(t.fragmentShader,"#include <normal_fragment_maps>",At(At(ot.normal_fragment_maps,"#elif defined( USE_NORMALMAP_TANGENTSPACE )","#elif defined( USE_NORMALMAP_TANGENTSPACE ) && !defined( USE_BUMPMAP )"),"normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );","vec3 parallaxUv = reliefParallaxPerturbNormal(faceDirection, normal);"))}},parsFragmentSnippet:()=>this.isDisabled()?"":(AW+`
`).replaceAll("PARALLAX_MAP_STEPS",this.stepCount.toString()).replaceAll("PARALLAX_MAP_B_STEPS",this.binaryStepCount.toString()),isCompatible:t=>t.isPhysicalMaterial,computeCacheKey:t=>""+!this.isDisabled()+t.bumpMap?.uuid+this.debugNormals+this.debugHitHeight+this.stepCount.toString()+this.binaryStepCount.toString(),onObjectRender:(t,i,n)=>{this.isDisabled()||ba({...this._defines},i)}},this.enabled=e,this._updateExtension=this._updateExtension.bind(this)}_updateExtension(){this._bumpMapExtension?.setDirty?.(),this._viewer?.setDirty()}onAdded(e){return e.materialManager.registerMaterialExtension(this._bumpMapExtension),super.onAdded(e)}onRemove(e){return e.materialManager.unregisterMaterialExtension(this._bumpMapExtension),super.onRemove(e)}},f.ParallaxMappingPlugin.PluginType="ReliefParallaxMapping",Th([de(f.ParallaxMappingPlugin.prototype._updateExtension),z(),ae("Enabled")],f.ParallaxMappingPlugin.prototype,"enabled",2),Th([Oe("Step count",[1,32],1),de(f.ParallaxMappingPlugin.prototype._updateExtension),z()],f.ParallaxMappingPlugin.prototype,"stepCount",2),Th([Oe("Binary search steps",[1,8],1),de(f.ParallaxMappingPlugin.prototype._updateExtension),z()],f.ParallaxMappingPlugin.prototype,"binaryStepCount",2),Th([de(f.ParallaxMappingPlugin.prototype._updateExtension),ae("Debug Normals")],f.ParallaxMappingPlugin.prototype,"debugNormals",2),Th([de(f.ParallaxMappingPlugin.prototype._updateExtension),ae("Debug Hit Height")],f.ParallaxMappingPlugin.prototype,"debugHitHeight",2),f.ParallaxMappingPlugin=Th([gt("Parallax Bump Mapping (MatExt)")],f.ParallaxMappingPlugin);const _W=`#include <simpleCameraHelpers>
uniform vec4 fragClippingPosition;uniform vec4 fragClippingParams;uniform float fragClippingCamAspect;
#if FRAG_CLIPPING_MODE == FragmentClippingMode.Circle
float fragClippingCircle(){vec2 pos=viewToScreen(vViewPosition.xyz).xy;float radius=fragClippingParams.x;vec2 center=fragClippingPosition.xy;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length(pos-center)-radius;}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Ellipse
float fragClippingEllipse(){vec2 pos=viewToScreen(vViewPosition.xyz).xy;vec2 radius=fragClippingParams.xy;vec2 center=fragClippingPosition.xy;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length((pos-center)/radius)-1.0;}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Rectangle
float fragClippingRectangle(){vec2 pos=viewToScreen(vViewPosition.xyz).xy;vec2 radius=fragClippingParams.xy;vec2 center=fragClippingPosition.xy;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;vec2 d=abs(pos-center)-radius;return min(max(d.x,d.y),0.0)+length(max(d,0.0));}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Plane
float fragClippingPlane(){vec3 pos=vViewPosition.xyz;vec3 normal=fragClippingParams.xyz;float d=dot(pos,normal)-fragClippingParams.w;return d;}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Sphere
float fragClippingSphere(){vec3 pos=vViewPosition.xyz;vec3 center=fragClippingPosition.xyz;float radius=fragClippingParams.x;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length(pos-center)-radius;}
#endif
`,bW=`float fragClippingDist=0.0;
#if FRAG_CLIPPING_MODE == FragmentClippingMode.Circle
fragClippingDist=fragClippingCircle();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Ellipse
fragClippingDist=fragClippingEllipse();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Rectangle
fragClippingDist=fragClippingRectangle();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Plane
fragClippingDist=fragClippingPlane();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Sphere
fragClippingDist=fragClippingSphere();
#endif
#if FRAG_CLIPPING_DEBUG
gl_FragColor=vec4(max(fragClippingDist,0.0),0.0,0.0,1.0);
#include <colorspace_fragment>
return;
#endif
#if FRAG_CLIPPING_INVERSE == 1
if(fragClippingDist>0.0)discard;
#else
if(fragClippingDist<0.0)discard;
#endif
`;var wW=Object.defineProperty,CW=Object.getOwnPropertyDescriptor,HI=(r,e,t,i)=>{for(var n=i>1?void 0:i?CW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&wW(e,t,n),n};f.FragmentClippingExtensionPlugin=class extends pt{constructor(){super(),this.enabled=!0,this._defines={FRAG_CLIPPING_DEBUG:0},this._uniforms={fragClippingPosition:{value:new rt},fragClippingParams:{value:new rt},fragClippingCamAspect:{value:1}},this._plane=new Ts,this._viewNormalMatrix=new mt,this._v4=new rt,this.materialExtension={parsFragmentSnippet:(e,t)=>!this.enabled||!t?.userData._fragmentClippingExt?.clipEnabled?"":Object.entries(Yd).map(i=>["FragmentClippingMode."+i[0],""+i[1]]).reduce((i,n)=>i.replace(n[0],n[1]),_W),shaderExtender:(e,t)=>{!this.enabled||!t?.userData._fragmentClippingExt?.clipEnabled||(e.fragmentShader=At(e.fragmentShader,"#glMarker mainStart",Object.entries(Yd).map(i=>["FragmentClippingMode."+i[0],""+i[1]]).reduce((i,n)=>i.replace(n[0],n[1]),`
`+bW),{append:!0}))},onObjectRender:(e,t)=>{let i=t.userData._fragmentClippingExt;if(t.userData.isGBufferMaterial&&e&&e.material&&!Array.isArray(e.material)&&(i=e.material?.userData._fragmentClippingExt),!!i?.clipEnabled){if(Array.isArray(i.clipPosition)?this._uniforms.fragClippingPosition.value.fromArray(i.clipPosition):this._uniforms.fragClippingPosition.value.copy(i.clipPosition),i.clipMode===3&&i.clipParams){const n=Array.isArray(i.clipParams)?this._v4.fromArray(i.clipParams):this._v4.copy(i.clipParams),s=this._viewer.scene.mainCamera.matrixWorldInverse;this._plane.normal.set(n.x,n.y,n.z),this._plane.constant=n.w,this._viewNormalMatrix.getNormalMatrix(s),this._plane.applyMatrix4(s,this._viewNormalMatrix),this._uniforms.fragClippingParams.value.set(this._plane.normal.x,this._plane.normal.y,this._plane.normal.z,this._plane.constant)}else Array.isArray(i.clipPosition)?this._uniforms.fragClippingParams.value.fromArray(i.clipParams):this._uniforms.fragClippingParams.value.copy(i.clipParams);this._viewer?.scene.mainCamera.isPerspectiveCamera?this._uniforms.fragClippingCamAspect.value=this._viewer?.scene.mainCamera.aspect:this._uniforms.fragClippingCamAspect.value=1,ba({...this._defines,FRAG_CLIPPING_MODE:+(i.clipMode??0),FRAG_CLIPPING_INVERSE:+(i.clipInvert??!1)},t)}},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData._fragmentClippingExt?.clipEnabled?"1":"0"),isCompatible:e=>e.isPhysicalMaterial||e.userData.isGBufferMaterial,getUiConfig:e=>{const t=this._viewer;e.userData._fragmentClippingExt===void 0&&(e.userData._fragmentClippingExt={});const i=e.userData._fragmentClippingExt,n={type:"folder",label:"Fragment Clipping",onChange:s=>{s.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i.clipEnabled||!1},set value(s){s!==i.clipEnabled&&(s?f.FragmentClippingExtensionPlugin.AddFragmentClipping(e)||t.dialog.alert("Cannot add FragmentClippingExtension."):(i.clipEnabled=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"dropdown",label:"Mode",children:Object.entries(Yd).map(s=>({label:s[0],value:s[1]})),hidden:()=>!i.clipEnabled,property:[i,"clipMode"]},{type:"vec4",label:"Position",bounds:[-1,1],hidden:()=>!i.clipEnabled,property:[i,"clipPosition"]},{type:"vec4",label:"Params",bounds:[0,1],hidden:()=>!i.clipEnabled,property:[i,"clipParams"]},{type:"toggle",label:"Invert",hidden:()=>!i.clipEnabled,property:[i,"clipInvert"]}]};return n}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}static AddFragmentClipping(e,t){const i=e?.userData;if(!i)return!1;i._fragmentClippingExt||(i._fragmentClippingExt={});const n=i._fragmentClippingExt;return n.clipEnabled=!0,n.clipPosition===void 0&&(n.clipPosition=[0,0,0,0]),n.clipParams===void 0&&(n.clipParams=[0,0,0,0]),n.clipMode===void 0!==void 0&&(n.clipMode=0),n.clipInvert===void 0!==void 0&&(n.clipInvert=!1),t&&Object.assign(n,t),e.setDirty&&e.setDirty(),!0}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Ih)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Ih.name),super.onRemove(e)}},f.FragmentClippingExtensionPlugin.PluginType="FragmentClippingExtensionPlugin1",f.FragmentClippingExtensionPlugin.FRAGMENT_CLIPPING_EXTENSION_GLTF_EXTENSION="WEBGI_materials_fragment_clipping_extension",HI([ae("Enabled",r=>({onChange:r.setDirty})),z()],f.FragmentClippingExtensionPlugin.prototype,"enabled",2),f.FragmentClippingExtensionPlugin=HI([gt("Fragment Clipping (MatExt)")],f.FragmentClippingExtensionPlugin);var Yd=(r=>(r[r.Circle=0]="Circle",r[r.Ellipse=1]="Ellipse",r[r.Rectangle=2]="Rectangle",r[r.Plane=3]="Plane",r[r.Sphere=4]="Sphere",r))(Yd||{});class xW{constructor(e){this.parser=e,this.name=Ih.name}async extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),f.FragmentClippingExtensionPlugin.AddFragmentClipping(t),ke.Deserialize(s,t.userData._fragmentClippingExt)}}const Ih={name:"WEBGI_materials_fragment_clipping",import:r=>new xW(r),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._fragmentClippingExt?.clipEnabled)return;t.extensions=t.extensions||{};const i=ke.Serialize(e.userData._fragmentClippingExt);t.extensions[Ih.name]=i,r.extensionsUsed[Ih.name]=!0}}),textures:void 0};var SW=Object.defineProperty,EW=Object.getOwnPropertyDescriptor,QI=(r,e,t,i)=>{for(var n=i>1?void 0:i?EW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&SW(e,t,n),n};f.VirtualCamerasPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.cameras=[],this._viewerListeners={preRender:()=>{if(this.isDisabled()||!this._viewer)return;const t=this._viewer;for(const i of this.cameras){if(!i.enabled)continue;const n=i.camera;try{this.dispatchEvent({type:"preRenderCamera",camera:i}),t.scene.renderCamera=n,t.renderManager.render(t.scene,!1);const s=t.renderManager.composer.readBuffer.texture;this.dispatchEvent({type:"preBlitCamera",camera:i,readBuffer:s}),t.renderManager.blit(i.target,{source:s}),this.dispatchEvent({type:"postRenderCamera",camera:i})}catch(s){if(t.console.error(s),i.enabled=!1,t.debug)throw s}}}},this._objectExtension={uuid:"VirtualCameraPluginExt",isCompatible:t=>t.isCamera,getUiConfig:t=>{if(t.isCamera)return[{type:"button",label:"Add Virtual Camera",hidden:()=>!!this.cameras.find(i=>i.camera===t),onClick:()=>{if(this._viewer)return this.addCamera(t,void 0,!0),t.setDirty&&t.setDirty(),()=>{this.removeCamera(t),t.setDirty&&t.setDirty()}}},{type:"button",label:"Virtual Camera Enabled",hidden:()=>!this.cameras.find(i=>i.camera===t),getValue:()=>{const i=this.cameras.find(n=>n.camera===t);return i?i.enabled:!1},setValue:()=>{const i=this.cameras.find(n=>n.camera===t);return i?(i.enabled=!i.enabled,i.enabled):!1}},{type:"button",label:"Remove Virtual Camera",hidden:()=>!this.cameras.find(i=>i.camera===t),onClick:()=>{if(this._viewer)return this.removeCamera(t),t.setDirty&&t.setDirty(),()=>{this.addCamera(t,void 0,!0),t.setDirty&&t.setDirty()}}}]}},this.enabled=e}onAdded(e){super.onAdded(e),e.object3dManager.registerObjectExtension(this._objectExtension)}onRemove(e){e.object3dManager.unregisterObjectExtension(this._objectExtension),super.onRemove(e)}addCamera(e,t,i=!1){if(!this._viewer)throw"Plugin not added to viewer";t=t??this._viewer.renderManager.composerTarget.clone(!0),t.name=e.name+"_virtualCamTarget";const n={camera:e,target:t,enabled:!0};return this.cameras.push(n),i&&this._viewer.getPlugin("RenderTargetPreviewPlugin")?.addTarget(t,e.name,!1,!1,!0),n}removeCamera(e){if(!this._viewer)throw"Plugin not added to viewer";const t=this.cameras.findIndex(i=>i.camera===e);if(t>=0){const i=this.cameras[t];return this.cameras.splice(t,1),this._viewer.getPlugin("RenderTargetPreviewPlugin")?.removeTarget(i.target),i.target.dispose(),!0}return!1}},f.VirtualCamerasPlugin.PluginType="VirtualCamerasPlugin",QI([ae()],f.VirtualCamerasPlugin.prototype,"enabled",2),f.VirtualCamerasPlugin=QI([gt("Virtual Cameras")],f.VirtualCamerasPlugin);var MW=Object.defineProperty,wo=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&MW(e,t,n),n};const Ug={cascades:3,shadowMapSize:2048,shadowBias:void 0,lightNear:void 0,lightFar:void 0,lightMargin:200},Da=(tr=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.parent=new Ri,this.maxFar=1e5,this.mode="practical",this.attachToFirstLight=!0,this.frustums=[],this.breaks=[],this.extendedBreaks=[],this.lights=[],this._lightRef=void 0,this._lightUpdate=t=>{t?.object===this.light&&this.refreshLights(t)},this.refreshLights=t=>{if(this._lightRef&&this._lightRef!==this.light&&(this._lightRef.removeEventListener("objectUpdate",this._lightUpdate),this._lightAutoAttached&&(this._lightAutoAttached=!1),this._lightRef=void 0),!this.light||(this._lightRef||(this.light.addEventListener("objectUpdate",this._lightUpdate),this._lightRef=this.light),this.isDisabled()))return;this.light.castShadow=!1,this.light.visible=!1,this.parent.visible=!0;let i=this.light.userData[tr.PluginType];i||(i={},this.light.userData[tr.PluginType]=i);const n={...Ug,...i};for(let a=0;a<n.cascades;a++){if(!this.lights[a]){const l=new il(16777215,1);l.name="CSM Light "+a,this.lights.push(l),this.parent.add(l),this.parent.add(l.target)}const o=this.lights[a];o.intensity=this.light.intensity,o.color.set(this.light.color),o.castShadow=!0,o.shadow.mapSize.width=n.shadowMapSize,o.shadow.mapSize.height=n.shadowMapSize,o.shadow.camera.near=n.lightNear??this.light.shadow.camera.near,o.shadow.camera.far=n.lightFar??this.light.shadow.camera.far,o.shadow.bias=n.shadowBias??this.light.shadow.bias,o.shadow.normalBias=this.light.shadow.normalBias,o.shadow.radius=this.light.shadow.radius}if(this.lights.length>n.cascades){const a=this.lights.splice(n.cascades,this.lights.length-n.cascades);for(const o of a)this.parent.remove(o.target),this.parent.remove(o)}const s=t?.change??t?.key;!s&&!["intensity","castShadow","mapSize","bias","radius","shadow","deserialize"].includes(s)&&this.cameraNeedsUpdate()},this._mainCameraChange=t=>{this.camera=t.camera,this.cameraNeedsUpdate()},this._cameraUpdated=!1,this._mainCameraUpdate=t=>{t.projectionUpdated!==!1?this.cameraNeedsUpdate():this.setDirty()},this.cameraNeedsUpdate=()=>{this._cameraUpdated=!0,this._viewer?.setDirty()},this._needsUpdate=!1,this.setDirty=()=>{const t=!this.isDisabled();t!==this._lastEnabled&&(this._lastEnabled=t,this.refreshLights(),t||(this.light&&(this.light.castShadow=!0,this.light.visible=!0,this.parent.visible=!1,this.light.setDirty&&this.light.setDirty()),this.extendedBreaks.length=0,this._sversion++,this.materialExtension.setDirty&&this.materialExtension.setDirty(),this._viewer?.setDirty())),t&&(this._needsUpdate=!0,this._viewer?.setDirty())},this._viewerListeners={preRender:()=>{if(this.isDisabled()||!this.light)return;let t=!1;this._cameraUpdated&&(this._updateFrustums(),t=!0),this._needsUpdate&&!this.update()&&(t=!0),t&&this._viewer?.renderManager.resetShadows()}},this._lastCenters=[],this._lightAutoAttached=!1,this.refreshAttachedLight=()=>{if(this.light&&this._lightAutoAttached){this.light.parent||(this.light=void 0,this._lightAutoAttached=!1);return}if(!this.attachToFirstLight)return;const t=this._viewer?.object3dManager.getLights()||[];for(const i of t)if(i.isDirectionalLight&&i.castShadow){if(i===this.light)return;this.light=i,this._lightAutoAttached=!0;return}},this._sversion=0,this._updateFrustums=()=>{if(!this.light)return;const{cascades:t=Ug.cascades}=this.light.userData[tr.PluginType]||{},i=this._getBreaks(t);this._initCascades(i),this._updateShadowBounds(),this.extendedBreaks.length=0;for(let n=0;n<i.length;n++){const s=i[n];this.extendedBreaks.push(new $(i[n-1]||0,s))}this._sversion++,this.materialExtension.setDirty&&this.materialExtension.setDirty(),this._cameraUpdated=!1,this.setDirty()},this.materialExtension={extraDefines:{CSM_CASCADES:()=>this.cascades.toString(),USE_CSM:()=>this.light&&!this.isDisabled()?"1":void 0,CSM_FADE:()=>this.fade?"1":void 0},extraUniforms:{},computeCacheKey:()=>(this.isDisabled()?"1":"0")+this.lights.length+(this.fade?"1":"0")+this.light?.uuid,onObjectRender:(t,i)=>{i.extraUniformsToUpload.CSM_cascades&&(i.extraUniformsToUpload.CSM_cascades.needsUpdate=!1),i.extraUniformsToUpload.cameraNear&&(i.extraUniformsToUpload.cameraNear.needsUpdate=!1),i.extraUniformsToUpload.shadowFar&&(i.extraUniformsToUpload.shadowFar.needsUpdate=!1),!(this.isDisabled()||!this.light)&&(i.extraUniformsToUpload||(i.extraUniformsToUpload={}),i.extraUniformsToUpload.CSM_cascades||(i.extraUniformsToUpload.CSM_cascades={value:[]}),i.extraUniformsToUpload.cameraNear||(i.extraUniformsToUpload.cameraNear={value:0}),i.extraUniformsToUpload.shadowFar||(i.extraUniformsToUpload.shadowFar={value:0}),i.__csmVersion||(i.__csmVersion=0),i.__csmVersion!==this._sversion&&(i.__csmVersion=this._sversion,i.extraUniformsToUpload.cameraNear.value=this.camera?.near??.01,i.extraUniformsToUpload.shadowFar.value=Math.min(this.camera?.far??1e3,this.maxFar),i.extraUniformsToUpload.CSM_cascades.value=this.extendedBreaks,i.extraUniformsToUpload.cameraNear.needsUpdate=!0,i.extraUniformsToUpload.shadowFar.needsUpdate=!0,i.extraUniformsToUpload.CSM_cascades.needsUpdate=!0))},isCompatible:t=>t.isMeshStandardMaterial||t.isMeshPhysicalMaterial||t.isMeshLambertMaterial||t.isMeshPhongMaterial},this.uiConfig={type:"folder",label:"Cascaded Shadows (CSM)",children:[...vi(this),{type:"button",label:()=>this.light?"Select Light":"No Light Attached",disabled:()=>!this.light,onClick:()=>{this.light&&this.light.dispatchEvent({type:"select",ui:!0,value:this.light,object:this.light})}}]},this._lightDirection=new x,this._cameraToLightMatrix=new pe,this._lightSpaceFrustum=new $d,this._center=new x,this._bbox=new en,this._uniformArray=[],this._logArray=[],this._lightOrientationMatrix=new pe,this._lightOrientationMatrixInverse=new pe,this._up=new x(0,1,0),this.injectInclude(),this._lastEnabled=e,this.enabled=e,this.mainFrustum=new $d}setLightParams(e,t){if(t=t||this.light,!t){this._viewer?.console.warn("CascadedShadowsPlugin: No light attached to CascadedShadowsPlugin");return}let i=t.userData[tr.PluginType];i||(i={},t.userData[tr.PluginType]=i),Object.assign(i,e),t===this.light&&this.refreshLights()}onAdded(e){super.onAdded(e),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),e.scene.addEventListener("mainCameraUpdate",this._mainCameraUpdate),e.renderManager.addEventListener("resize",this.cameraNeedsUpdate),this.camera=e.scene.mainCamera,e.materialManager.registerMaterialExtension(this.materialExtension),e.object3dManager.addEventListener("lightAdd",this.refreshAttachedLight),e.object3dManager.addEventListener("lightRemove",this.refreshAttachedLight),this.refreshAttachedLight(),e.scene.addObject(this.parent,{addToRoot:!0,indexInParent:0}),this.refreshLights()}onRemove(e){e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),e.scene.removeEventListener("mainCameraUpdate",this._mainCameraUpdate),e.renderManager.removeEventListener("resize",this.cameraNeedsUpdate),e.materialManager.unregisterMaterialExtension(this.materialExtension),e.object3dManager.removeEventListener("lightAdd",this.refreshAttachedLight),e.object3dManager.removeEventListener("lightRemove",this.refreshAttachedLight),this.refreshAttachedLight(),this.light&&this._lightAutoAttached&&(this.light=void 0,this._lightAutoAttached=!1);for(const t of this.lights)this.parent.remove(t.target),this.parent.remove(t);this.parent.clear(),this.parent.removeFromParent(),this.camera=void 0,super.onRemove(e)}_initCascades(e){const t=this.camera;return t?(t.updateProjectionMatrix&&t.updateProjectionMatrix(),this.mainFrustum.setFromProjectionMatrix(t.projectionMatrix,this.maxFar),this.mainFrustum.split(e,this.frustums),this.frustums):this.frustums}_updateShadowBounds(){for(let e=0;e<this.frustums.length;e++){const i=this.lights[e].shadow.camera,n=this.frustums[e],s=n.vertices.near,a=n.vertices.far,o=a[0];let l;o.distanceTo(a[2])>o.distanceTo(s[2])?l=a[2]:l=s[2];let c=o.distanceTo(l);if(this.fade&&this.camera){const h=this.camera,u=Math.max(h.far,this.maxFar),d=n.vertices.far[0].z/(u-h.near),p=.25*Math.pow(d,2)*(u-h.near);c+=p}i.left=-c/2,i.right=c/2,i.top=c/2,i.bottom=-c/2,i.updateProjectionMatrix()}}_getBreaks(e){this.breaks.length=0;const t=this.camera;if(!t)return this.breaks;const i=Math.min(t.far,this.maxFar);let n=this.mode;switch(n==="custom"&&this.customSplitsCallback===void 0&&(console.error("CSM: Custom split scheme callback not defined."),n="practical"),n){case"uniform":this._uniformSplit(e,t.near,i,this.breaks);break;case"logarithmic":this._logarithmicSplit(e,t.near,i,this.breaks);break;case"practical":default:this._practicalSplit(e,t.near,i,.5,this.breaks);break;case"custom":this.customSplitsCallback&&this.customSplitsCallback(e,t.near,i,this.breaks);break}return this.breaks}_uniformSplit(e,t,i,n){for(let s=1;s<e;s++)n.push((t+(i-t)*s/e)/i);n.push(1)}_logarithmicSplit(e,t,i,n){for(let s=1;s<e;s++)n.push(t*(i/t)**(s/e)/i);n.push(1)}_practicalSplit(e,t,i,n,s){this._uniformArray.length=0,this._logArray.length=0,this._logarithmicSplit(e,t,i,this._logArray),this._uniformSplit(e,t,i,this._uniformArray);for(let a=1;a<e;a++)s.push(Ut.lerp(this._uniformArray[a-1],this._logArray[a-1],n));s.push(1)}update(){this._needsUpdate=!1;const e=this.camera;if(!e||!this.light)return!0;const t=this.frustums,{shadowMapSize:i=Ug.shadowMapSize,lightMargin:n=Ug.lightMargin}=this.light.userData[tr.PluginType]||{};{this.light.updateMatrixWorld();const o=this.light.getWorldPosition(this._center);this.light.target.updateMatrixWorld(),this.light.target.getWorldPosition(this._lightDirection),this._lightOrientationMatrix.lookAt(o,this._lightDirection,this._up),this._lightOrientationMatrixInverse.copy(this._lightOrientationMatrix).invert(),this._lightDirection.sub(o).normalize()}const s=[];for(let o=0;o<t.length;o++){const l=this.lights[o],c=l.shadow.camera,h=(c.right-c.left)/i,u=(c.top-c.bottom)/i;this._cameraToLightMatrix.multiplyMatrices(this._lightOrientationMatrixInverse,e.matrixWorld),t[o].toSpace(this._cameraToLightMatrix,this._lightSpaceFrustum);const d=this._lightSpaceFrustum.vertices.near,p=this._lightSpaceFrustum.vertices.far;this._bbox.makeEmpty();for(let m=0;m<4;m++)this._bbox.expandByPoint(d[m]),this._bbox.expandByPoint(p[m]);this._bbox.getCenter(this._center),this._center.z=this._bbox.max.z+n,this._center.x=Math.floor(this._center.x/h)*h,this._center.y=Math.floor(this._center.y/u)*u,this._center.applyMatrix4(this._lightOrientationMatrix),s.push(this._center.clone()),l.position.copy(this._center),l.target.position.copy(this._center).add(this._lightDirection)}let a=!0;if(s.length===this._lastCenters.length){for(let o=0;o<s.length;o++)if(Math.abs(s[o].x-this._lastCenters[o].x)+Math.abs(s[o].y-this._lastCenters[o].y)+Math.abs(s[o].z-this._lastCenters[o].z)>.001){a=!1;break}}else a=!1;return this._lastCenters=s,a}get cascades(){return this.isDisabled()||!this.light?0:this.frustums.length}injectInclude(){ot.lights_fragment_begin.includes("defined( USE_CSM ) && defined( CSM_CASCADES )")||(ot.lights_fragment_begin=At(ot.lights_fragment_begin,`#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
`,`
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES )

	DirectionalLight directionalLight;
	float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear);
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif

	#if defined( USE_SHADOWMAP ) && defined( CSM_FADE )
		vec2 cascade;
		float cascadeCenter;
		float closestEdge;
		float margin;
		float csmx;
		float csmy;

		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];
			getDirectionalLightInfo( directionalLight, directLight );

			#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
			
            #if ( UNROLLED_LOOP_INDEX < CSM_CASCADES )

				// NOTE: Depth gets larger away from the camera.
				// cascade.x is closer, cascade.y is further
				cascade = CSM_cascades[ UNROLLED_LOOP_INDEX ];
				cascadeCenter = ( cascade.x + cascade.y ) / 2.0;
				closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y;
				margin = 0.25 * pow( closestEdge, 2.0 );
				csmx = cascade.x - margin / 2.0;
				csmy = cascade.y + margin / 2.0;
				if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) {

					float dist = min( linearDepth - csmx, csmy - linearDepth );
					float ratio = clamp( dist / margin, 0.0, 1.0 );

					vec3 prevColor = directLight.color;
					directionalLightShadow = directionalLightShadows[ i ];
					directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter;
					directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 );

					ReflectedLight prevLight = reflectedLight;
					RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

					bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter;
					float blendRatio = shouldBlend ? ratio : 1.0;

					reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio );
					reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio );
					reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio );
					reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio );

				}
				
				
            #else 
            
                directionalLightShadow = directionalLightShadows[ i ];
                directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
    
                RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

			#endif
			
			#endif

		}
		#pragma unroll_loop_end
	#elif defined (USE_SHADOWMAP)

		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];
			getDirectionalLightInfo( directionalLight, directLight );

			#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )

                directionalLightShadow = directionalLightShadows[ i ];
				
				#if ( UNROLLED_LOOP_INDEX < CSM_CASCADES )

					if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

				#else

					directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

				#endif
				
			#endif

		}
		#pragma unroll_loop_end

	#elif ( NUM_DIR_LIGHT_SHADOWS > 0 )
		// note: no loop here - all CSM lights are in fact one light only
		getDirectionalLightInfo( directionalLights[0], directLight );
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

	#endif

	#if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS)
		// compute the lights not casting shadows (if any)

		#pragma unroll_loop_start
		for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];

			getDirectionalLightInfo( directionalLight, directLight );

			RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

		}
		#pragma unroll_loop_end

	#endif

#endif


#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !( defined( USE_CSM ) && defined( CSM_CASCADES ) )
`),ot.lights_pars_begin=`
#if defined( USE_CSM ) && defined( CSM_CASCADES )
uniform vec2 CSM_cascades[CSM_CASCADES];
uniform float cameraNear;
uniform float shadowFar;
#endif
	`+ot.lights_pars_begin)}},tr.PluginType="CascadedShadowsPlugin",tr);wo([ae(),z(),de("setDirty")],Da.prototype,"enabled"),wo([de("cameraNeedsUpdate"),z(),Fe()],Da.prototype,"maxFar"),wo([de("cameraNeedsUpdate"),z(),Oi(void 0,["uniform","logarithmic","practical"])],Da.prototype,"mode"),wo([ae(),z()],Da.prototype,"attachToFirstLight"),wo([de("cameraNeedsUpdate"),z(),ae()],Da.prototype,"fade"),wo([de("refreshLights")],Da.prototype,"light"),wo([de("cameraNeedsUpdate")],Da.prototype,"customSplitsCallback"),wo([lt()],Da.prototype,"refreshAttachedLight");let TW=Da;class $d{constructor(e={}){this._inverseProjectionMatrix=new pe,this.vertices={near:[new x,new x,new x,new x],far:[new x,new x,new x,new x]},e.projectionMatrix!==void 0&&this.setFromProjectionMatrix(e.projectionMatrix,e.maxFar||1e4)}setFromProjectionMatrix(e,t){const i=e.elements[11]===0;return this._inverseProjectionMatrix.copy(e).invert(),this.vertices.near[0].set(1,1,-1),this.vertices.near[1].set(1,-1,-1),this.vertices.near[2].set(-1,-1,-1),this.vertices.near[3].set(-1,1,-1),this.vertices.near.forEach(n=>{n.applyMatrix4(this._inverseProjectionMatrix)}),this.vertices.far[0].set(1,1,1),this.vertices.far[1].set(1,-1,1),this.vertices.far[2].set(-1,-1,1),this.vertices.far[3].set(-1,1,1),this.vertices.far.forEach(n=>{n.applyMatrix4(this._inverseProjectionMatrix);const s=Math.abs(n.z);i?n.z*=Math.min(t/s,1):n.multiplyScalar(Math.min(t/s,1))}),this.vertices}split(e,t){for(;e.length>t.length;)t.push(new $d);t.length=e.length;for(let i=0;i<e.length;i++){const n=t[i];if(i===0)for(let s=0;s<4;s++)n.vertices.near[s].copy(this.vertices.near[s]);else for(let s=0;s<4;s++)n.vertices.near[s].lerpVectors(this.vertices.near[s],this.vertices.far[s],e[i-1]);if(i===e.length-1)for(let s=0;s<4;s++)n.vertices.far[s].copy(this.vertices.far[s]);else for(let s=0;s<4;s++)n.vertices.far[s].lerpVectors(this.vertices.near[s],this.vertices.far[s],e[i])}}toSpace(e,t){for(let i=0;i<4;i++)t.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(e),t.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(e)}}var IW=Object.defineProperty,jI=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&IW(e,t,n),n};const N_=(Mo=class extends pt{constructor(){super(),this.enabled=!0,this._uiNeedRefresh=!1,this.applyOnLoad=!0,this.applyOnLoadForce=!1,this.variations=[],this._selectedMaterial=()=>{const e=this._picking?.getSelectedObject();if(e){if(e.isMaterial)return e;{const t=e?.material||void 0;return Array.isArray(t)?t[0]:t}}},this._uicShowAllVariations=!1,this.uiConfig={label:"Material Configurator",type:"folder",children:[()=>[{type:"input",label:"uuid",property:[this._selectedMaterial(),"uuid"],hidden:()=>!this._selectedMaterial(),disabled:!0},this.createVariationsUiConfig(this.getSelectedVariation())??(this._uicShowAllVariations?{}:{type:"button",label:"Select a material to see or add variations",readOnly:!0}),this._uicShowAllVariations&&!this._selectedMaterial()?this.variations.map(e=>this.createVariationsUiConfig(e)):[],{type:"button",label:"Clear variations",hidden:()=>!this.getSelectedVariation(),value:async()=>{const e=this.getSelectedVariation();e&&await this._viewer.dialog.confirm("Material configurator: Remove all variations for this material?")&&(e.materials=[]),this.refreshUi()}},{type:"button",label:"Remove completely",hidden:()=>!this.getSelectedVariation(),value:async()=>{const e=this.getSelectedVariation();e&&await this._viewer.dialog.confirm("Material configurator: Remove this variation?")&&this.removeVariation(e)}},{type:"button",label:"Add Variation",hidden:()=>!this._selectedMaterial(),value:async()=>{const e=this._selectedMaterial();e&&(!e.name&&!await this._viewer?.dialog.confirm("Material configurator: Material has no name. Use uuid instead?")||this.addVariation(e))}},{type:"button",label:"Refresh Ui",value:()=>this.refreshUi()},{type:"button",label:"Apply All",value:()=>{this.variations.forEach(e=>this.applyVariation(e,e.materials[0].uuid))}},{type:"checkbox",label:"Show All",hidden:()=>this._selectedMaterial(),property:()=>[this,"_uicShowAllVariations"],onChange:async()=>this.uiConfig?.uiRefresh?.()}]]},this.addEventListener("deserialize",this.refreshUi),this.refreshUi=this.refreshUi.bind(this),this._preFrame=this._preFrame.bind(this),this._refreshUi=this._refreshUi.bind(this),this._refreshUiConfig=this._refreshUiConfig.bind(this)}onAdded(e){super.onAdded(e),e.forPlugin(ws,t=>{this._picking=t,this._picking?.addEventListener("selectedObjectChanged",this._refreshUiConfig)},()=>{this._picking?.removeEventListener("selectedObjectChanged",this._refreshUiConfig),this._picking=void 0},this),this._previewGenerator=new JS,e.addEventListener("preFrame",this._refreshUi),e.addEventListener("preFrame",this._preFrame)}reapplyAll(){this.variations.forEach(async e=>{e.selectedIndex!==void 0&&this.applyVariation(e,e.selectedIndex)})}fromJSON(e,t){return this.variations=[],super.fromJSON(e,t)?((this.applyOnLoadForce&&e.applyOnLoad!==!1||e.applyOnLoad!==void 0&&this.applyOnLoad)&&this.reapplyAll(),this):null}onRemove(e){return this._previewGenerator?.dispose(),this._previewGenerator=void 0,this._picking?.removeEventListener("selectedObjectChanged",this._refreshUiConfig),this.removeEventListener("deserialize",this.refreshUi),e.removeEventListener("preFrame",this._refreshUi),e.removeEventListener("preFrame",this._preFrame),this._picking=void 0,super.onRemove(e)}findVariation(e){return e?this.variations.find(t=>t.regex??!0?e.match(typeof t.uuid=="string"?"^"+t.uuid+"$":t.uuid)!==null:t.uuid===e):void 0}getSelectedVariation(){const e=this._selectedMaterial();if(!e)return;const t=this.findVariation(e.uuid)||this.findVariation(e.name);return t&&t.regex===void 0&&(t.regex=!0),t}applyVariation(e,t,i,n){const s=this._viewer?.materialManager;if(!s)return!1;const a=this.findMaterialVariation(t,e);if(!a)return!1;i&&(e.selectedIndex=e.materials.indexOf(a));const o=n?.from!==void 0?this.findMaterialVariation(n.from,e):void 0;return s.applyMaterial(a,e.uuid,e.regex??!0,n?.from!==void 0?{...n,from:o}:n)}findMaterialVariation(e,t){return typeof e=="string"?t.materials.find(i=>i.uuid===e):t.materials[e]}async applyVariationAnimate(e,t,i=500){e._animation&&e._animation.stop();const n=this._viewer?.getPlugin(Vr);if(!n)throw new Error("MaterialConfiguratorBasePlugin - PopmotionPlugin is required for animation, please add it to the viewer.");this._viewer?.getPlugin(f.FrameFadePlugin)?.disable(Mo.PluginType);const s=n.animateNumber({duration:i,onUpdate:(a,o)=>{this.applyVariation(e,t,!0,{t:a,dt:o})},onComplete:()=>{this.applyVariation(e,t,!0,{t:1,dt:0})},onEnd:()=>{e._animation===s&&(e._animation=void 0)}});e._animation=s,await e._animation?.promise,this._viewer?.getPlugin(f.FrameFadePlugin)?.enable(Mo.PluginType)}getPreview(e,t,i=!0){if(!this._viewer)return"";const n=e;if(!n)return"";let s="";if(t.startsWith("generate:"))s=this._previewGenerator.generate(n,this._viewer.renderManager.renderer,this._viewer.scene.environment,t.split(":")[1]);else{const a=n[t]||"#ff00ff";s=a.image?sS(a.image,100):"",s.length||(s=oS(a.isColor?a.getHexString():a))}return i&&this._viewer.setDirty(),s}refreshUi(){this.isDisabled()||!this._viewer||it(this.uiConfig.hidden)||(this.dispatchEvent({type:"refreshUi"}),this._uiNeedRefresh=!0)}_refreshUiConfig(){this.isDisabled()||this.uiConfig.uiRefresh?.(!0,"postFrame",500)}async _refreshUi(){return this.isDisabled()||!this._viewer||!this._uiNeedRefresh?!1:(this._uiNeedRefresh=!1,this._refreshUiConfig(),!0)}_preFrame(){if(this.isDisabled()||!this._viewer?.timeline.shouldRun()||!this.variations.length)return!1;const e=this._viewer?.timeline.time,t=this._viewer?.timeline.delta||0,i=this._viewer?.timeline.resetOnEnd??!1;let n=!1;for(const s of this.variations){if(!s.timeline?.length)continue;const a=s.selectedIndex,o=s.timeline.sort((d,p)=>-d.time+p.time),l=o.find(d=>d.time<=e),c=l?o.indexOf(l):-1,h=c<o.length-1&&c>=0?o[c+1]:i&&c>0?o[0]:void 0,u=!this._viewer?.timeline.running;if(l){const d=typeof a>"u"||l.index!==a&&(typeof a!="number"||l.index!==s.materials[a]?.uuid);if(u||d){const p=l.time,m=l.duration??.5;let A=m<1e-6?1:(e-p)/m,g=m<1e-6?0:t/m;A>1&&(A=1),g<1e-6&&(g=1/60),this.applyVariation(s,l.index,A>=1-1e-5,{t:A,dt:g,from:u?h?.index:void 0,rm:this._viewer?.renderManager}),n=!0}}}return n}createVariationsUiConfig(e){if(e)return{type:"folder",label:e.title,uuid:e.uuid,children:[{type:"input",label:"mapping",property:()=>[e,"uuid"],onChange:async()=>this.refreshUi()},{type:"input",label:"title",property:()=>[e,"title"],onChange:async()=>this.refreshUi()},{type:"dropdown",label:"Preview Type",property:()=>[e,"preview"],onChange:async()=>this.refreshUi(),children:["generate:sphere","generate:cube","color","map","emissive",...Object.keys(ai.MaterialProperties).filter(t=>t.endsWith("Map"))].map(t=>({label:t,value:t}))},{type:"checkbox",label:"regex mapping",property:()=>[e,"regex"],onChange:async()=>this.refreshUi()},...e.materials.map(t=>t.uiConfig?Object.assign(t.uiConfig,{expanded:!1}):{})]}}removeVariationForMaterial(e){let t=this.findVariation(e.uuid);!t&&e.name.length>0&&(t=this.findVariation(e.name)),t&&this.removeVariation(t)}removeVariation(e){e&&(this.variations.splice(this.variations.indexOf(e),1),this.refreshUi())}addVariation(e,t,i=!0){const n=i&&e?.clone?e.clone():e;if(e&&n){let s=this.findVariation(t??e.uuid);!s&&!t&&e.name.length>0&&(s=this.findVariation(e.name)),s||(s=this.createVariation(e,t)),s.materials.push(n),this.refreshUi()}}createVariation(e,t){return this.variations.push({uuid:t??e.name.length>0?Nu(e.name):e.uuid,title:e.name.length>0?e.name:"No Name",preview:"generate:sphere",materials:[],regex:!0}),this.variations[this.variations.length-1]}},Mo.PluginType="MaterialConfiguratorPlugin",Mo);jI([z()],N_.prototype,"applyOnLoad"),jI([z()],N_.prototype,"variations");let PW=N_;var DW=Object.defineProperty,WI=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&DW(e,t,n),n};const fb=class fb extends pt{constructor(){super(),this.enabled=!0,this._uiNeedRefresh=!1,this.refreshScene=!0,this.applyOnLoad=!0,this.variations=[],this._selectedSwitchNode=()=>{const e=this._picking?.getSelectedObject();if(!e?.isObject3D)return;const t=this.variations.map(n=>n.name);let i;return e.traverseAncestors(n=>{i||n.name&&t.includes(n.name)&&(i=n)}),i},this.autoSnapIcons=!1,this.uiConfig={label:"Switch Node Plugin",type:"folder",children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"]},()=>[{type:"folder",label:"All nodes",expanded:!0,children:[this.variations.map(e=>({type:"input",label:e.title,property:[e,"name"],onChange:()=>this.refreshUi()}))]},{type:"button",label:"Add Node",value:()=>{this.addNode({name:"switch_node",selected:"",title:"Switch Node",camView:"front",camDistance:1})}},{type:"button",label:"Refresh UI",value:()=>this.refreshUi()},{type:"input",label:"Selected node title",hidden:()=>!this._selectedSwitchNode(),property:()=>{const e=this._selectedSwitchNode();return e?[this.variations.find(t=>t.name===e.name),"title"]:[]},onChange:()=>this.refreshUi()},{type:"slider",bounds:[.01,2],stepSize:.01,label:"Cam Distance",hidden:()=>!this._selectedSwitchNode(),property:()=>{const e=this._selectedSwitchNode();return e?[this.variations.find(t=>t.name===e.name),"camDistance"]:[]}},{type:"dropdown",label:"Cam View",hidden:()=>!this._selectedSwitchNode(),property:()=>{const e=this._selectedSwitchNode();return e?[this.variations.find(t=>t.name===e.name),"camView"]:[]},onChange:()=>this.refreshUi(),children:["top","bottom","front","back","left","right"].map(e=>({label:e,value:e}))}]]},this._postFrame=this._postFrame.bind(this),this.refreshUiConfig=this.refreshUiConfig.bind(this),this.addEventListener("deserialize",async()=>{this.refreshUi()})}onAdded(e){super.onAdded(e),e.forPlugin(ws,t=>{this._picking=t,this._picking?.addEventListener("selectedObjectChanged",this.refreshUiConfig)},()=>{this._picking?.removeEventListener("selectedObjectChanged",this.refreshUiConfig),this._picking=void 0},this),e.addEventListener("postFrame",this._postFrame)}onRemove(e){this._picking?.removeEventListener("selectedObjectChanged",this.refreshUiConfig),this._picking=void 0,e.removeEventListener("postFrame",this._postFrame),super.onRemove(e)}_postFrame(){this._uiNeedRefresh&&this._refreshUi()}selectNode(e,t,i=!0){const n=this._viewer?.scene.getObjectByName(e.name);if(!n||n.children.length<1)return;const s=typeof t=="number"?n.children[t]:n.children.find(o=>o.name===t||o.uuid===t);if(!s)return this._viewer?.console.warn("SwitchNodePlugin: child not found",t),!1;e.selected=s.name||s.uuid;let a=!1;for(const o of n.children){const l=o.visible;o.visible=(o.name||o.uuid)===e.selected,a=a||l!==o.visible}return a&&i&&this._viewer.scene.setDirty({refreshScene:this.refreshScene,frameFade:!0}),a}reapplyAll(){this.variations.forEach(e=>this.selectNode(e,e.selected||0,!1)),this._viewer.scene.setDirty({refreshScene:!0,frameFade:!0})}fromJSON(e,t){return this.variations=[],super.fromJSON(e,t)?(e.applyOnLoad===void 0&&(this.applyOnLoad=!0),this.applyOnLoad&&this.reapplyAll(),this):null}refreshUi(){this.enabled&&(this._uiNeedRefresh=!0)}_refreshUi(){return!this.enabled||!this._viewer?!1:(this._uiNeedRefresh=!1,this.autoSnapIcons&&this.snapIcons(),this.refreshUiConfig(),!0)}refreshUiConfig(){this.enabled&&this.uiConfig.uiRefresh?.()}getPreview(e,t,i=!0){if(!this._viewer||!e)return"";const n=e.camView,s=new x((n.includes("right")?1:0)-(n.includes("left")?1:0),(n.includes("top")?1:0)-(n.includes("bottom")?1:0),(n.includes("front")?1:0)-(n.includes("back")?1:0));e.camDistance||(e.camDistance=1);const a=Pv(this._viewer.renderManager.renderer,t,this._viewer?.scene,7,s.multiplyScalar(e.camDistance*2));return i&&this._viewer.setDirty(),a}addNode(e,t=!0){this.variations.push(e),t&&this.refreshUi()}snapIcons(){for(const e of this.variations){const t=this._viewer.scene.getObjectByName(e.name);if(!t){console.warn("no object found for variation, skipping",e);continue}t.children.length<1&&console.warn("SwitchNode does not have enough children",e);for(const i of t.children){if(i.userData.__icon)continue;const n=this.getPreview(e,i,!1);n&&(i.userData.__icon=n)}}}};fb.PluginType="SwitchNodePlugin";let Kd=fb;WI([z()],Kd.prototype,"refreshScene"),WI([z()],Kd.prototype,"variations");function k_(r,e,t,i,n){const s=r.getAttribute(e),a=Array.isArray(i)?i.length/t:i.count;return s&&s.count===a?(s.set(Array.isArray(i)?i:i.array),s.needsUpdate=!0):r.setAttribute(e,Array.isArray(i)?new Me(i,t):i),s}function RW(r,e){const t=r.index;t&&t.count===(Array.isArray(e)?e.length:e.count)?(t.set(Array.isArray(e)?e:e.array),t.needsUpdate=!0):r.setIndex(e)}function G_(r,e){const t=r.uiConfig;if(!t)return;let i=t.children?.find(n=>typeof n=="object"&&n.tags?.includes("generatedGeometry"));if(!i){i={type:"folder",label:"Generation Params",expanded:!0,tags:["generatedGeometry"],children:[]};const n=t.children?.findIndex(s=>typeof s=="object"&&(s.type==="divider"||s.type==="separator"))??-1;n>=0?t.children?.splice(n,0,i):t.children?.push(i)}r.userData.__generationParamsUiType!==r.userData.generationParams.type&&(i.children=e(),r.userData.__generationParamsUiType=r.userData.generationParams.type,i.uiRefresh?.(!0,"postFrame"))}function BW(r){const e=r.uiConfig;if(!e)return;const t=e.children?.findIndex(i=>typeof i=="object"&&i.tags?.includes("generatedGeometry"))??-1;t>=0&&(e.children?.splice(t,1),e.uiRefresh?.(!0,"postFrame"))}class gr{constructor(e){this.type=e,this.defaultMeshClass=()=>zm,this.defaultMaterialClass=()=>ai,this.defaultGeometryClass=()=>_d}createUiConfig(e){if(!e.userData.generationParams)return[];const t=vi(e.userData.generationParams)?.flatMap(i=>it(i)).filter(i=>it(i.property)?.[1]!=="type")||[];return t.forEach(i=>{i.onChange=()=>this.generate(e)}),t}generate(e,t={}){const i=e??new _d;if(t.type&&t.type!==this.type)return console.error("Cannot change type of generated geometry here, use the plugin instead"),i;i.userData.generationParams||(i.userData.generationParams={type:this.type}),i.userData.generationParams.type=this.type;const n={...this.defaultParams,...i.userData.generationParams,...t,type:this.type},{indices:s,vertices:a,normals:o,uvs:l,groups:c,positions:h}=this._generateData(n);if(h!==void 0&&i.setPositions?i.setPositions(h):(s&&RW(i,s),a&&k_(i,"position",3,a),o&&k_(i,"normal",3,o),l&&k_(i,"uv",2,l)),c){i.clearGroups();for(const d of c)i.addGroup(d.start,d.count,d.materialIndex)}return i.computeBoundingBox&&i.computeBoundingBox(),i.computeBoundingSphere&&i.computeBoundingSphere(),Object.assign(i.userData.generationParams,n),G_(i,()=>this.createUiConfig(i)),i.setDirty(),i}setDefaultParams(e){return Object.assign(this.defaultParams,e),this}}class qI extends gr{constructor(e="torus",t){super(e),this.defaultParams={radius:1,tube:.4,radialSegments:12,tubularSegments:48,arc:Math.PI*2},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,tube:i,arc:n}=e;let{radialSegments:s,tubularSegments:a}=e;s=Math.floor(s),a=Math.floor(a);const o=[],l=[],c=[],h=[],u=new x,d=new x,p=new x;for(let m=0;m<=s;m++)for(let A=0;A<=a;A++){const g=A/a*n,y=m/s*Math.PI*2;d.x=(t+i*Math.cos(y))*Math.cos(g),d.y=(t+i*Math.cos(y))*Math.sin(g),d.z=i*Math.sin(y),l.push(d.x,d.y,d.z),u.x=t*Math.cos(g),u.y=t*Math.sin(g),p.subVectors(d,u).normalize(),c.push(p.x,p.y,p.z),h.push(A/a),h.push(m/s)}for(let m=1;m<=s;m++)for(let A=1;A<=a;A++){const g=(a+1)*m+A-1,y=(a+1)*(m-1)+A-1,_=(a+1)*(m-1)+A,v=(a+1)*m+A;o.push(g,y,v),o.push(y,_,v)}return{indices:o,vertices:l,normals:c,uvs:h}}}class XI extends gr{constructor(e="circle",t){super(e),this.defaultParams={radius:1,segments:32,thetaStart:0,thetaLength:Math.PI*2},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,thetaStart:i,thetaLength:n}=e,s=Math.max(3,e.segments),a=[],o=[],l=[],c=[],h=new x,u=new $;o.push(0,0,0),l.push(0,0,1),c.push(.5,.5);for(let d=0,p=3;d<=s;d++,p+=3){const m=i+d/s*n;h.x=t*Math.cos(m),h.y=t*Math.sin(m),o.push(h.x,h.y,h.z),l.push(0,0,1),u.x=(o[p]/t+1)/2,u.y=(o[p+1]/t+1)/2,c.push(u.x,u.y)}for(let d=1;d<=s;d++)a.push(d,d+1,0);return{indices:a,vertices:o,normals:l,uvs:c}}}class YI extends gr{constructor(e="box",t){super(e),this.defaultParams={width:1,height:1,depth:1,widthSegments:1,heightSegments:1,depthSegments:1},t&&Object.assign(this.defaultParams,t)}_buildPlane(e,t,i,n,s,a,o,l,c,h,u,d){const{indices:p,vertices:m,normals:A,uvs:g,numberOfVertices:y,groupStart:_,groups:v}=e,b=o/h,T=l/u,E=o/2,M=l/2,S=c/2,w=h+1,C=u+1;let D=0,O=0;const F=new x;for(let G=0;G<C;G++){const j=G*T-M;for(let W=0;W<w;W++){const K=W*b-E;F[t]=K*s,F[i]=j*a,F[n]=S,m.push(F.x,F.y,F.z),F[t]=0,F[i]=0,F[n]=c>0?1:-1,A.push(F.x,F.y,F.z),g.push(W/h),g.push(1-G/u),D+=1}}for(let G=0;G<u;G++)for(let j=0;j<h;j++){const W=y+j+w*G,K=y+j+w*(G+1),q=y+(j+1)+w*(G+1),oe=y+(j+1)+w*G;p.push(W,K,oe),p.push(K,q,oe),O+=6}v.push({start:_,count:O,materialIndex:d}),e.groupStart+=O,e.numberOfVertices+=D}_generateData(e){const{width:t,height:i,depth:n}=e;let{widthSegments:s,heightSegments:a,depthSegments:o}=e;s=Math.floor(s),a=Math.floor(a),o=Math.floor(o);const l={indices:[],vertices:[],normals:[],uvs:[],numberOfVertices:0,groupStart:0,groups:[]};return this._buildPlane(l,"z","y","x",-1,-1,n,i,t,o,a,0),this._buildPlane(l,"z","y","x",1,-1,n,i,-t,o,a,1),this._buildPlane(l,"x","z","y",1,1,t,n,i,s,o,2),this._buildPlane(l,"x","z","y",1,-1,t,n,-i,s,o,3),this._buildPlane(l,"x","y","z",1,-1,t,i,n,s,a,4),this._buildPlane(l,"x","y","z",-1,-1,t,i,-n,s,a,5),l}}class $I extends gr{constructor(e="sphere",t){super(e),this.defaultParams={radius:1,widthSegments:32,heightSegments:16,phiStart:0,phiLength:Math.PI*2,thetaStart:0,thetaLength:Math.PI},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,phiStart:i,phiLength:n,thetaStart:s,thetaLength:a}=e;let{widthSegments:o,heightSegments:l}=e;o=Math.max(3,Math.floor(o)),l=Math.max(2,Math.floor(l));const c=Math.min(s+a,Math.PI);let h=0;const u=[],d=new x,p=new x,m=[],A=[],g=[],y=[];for(let _=0;_<=l;_++){const v=[],b=_/l;let T=0;_===0&&s===0?T=.5/o:_===l&&c===Math.PI&&(T=-.5/o);for(let E=0;E<=o;E++){const M=E/o;d.x=-t*Math.cos(i+M*n)*Math.sin(s+b*a),d.y=t*Math.cos(s+b*a),d.z=t*Math.sin(i+M*n)*Math.sin(s+b*a),A.push(d.x,d.y,d.z),p.copy(d).normalize(),g.push(p.x,p.y,p.z),y.push(M+T,1-b),v.push(h++)}u.push(v)}for(let _=0;_<l;_++)for(let v=0;v<o;v++){const b=u[_][v+1],T=u[_][v],E=u[_+1][v],M=u[_+1][v+1];(_!==0||s>0)&&m.push(b,T,M),(_!==l-1||c<Math.PI)&&m.push(T,E,M)}return{indices:m,vertices:A,normals:g,uvs:y}}}class KI extends gr{constructor(e="plane",t){super(e),this.defaultParams={width:1,height:1,widthSegments:2,heightSegments:2},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=e.width/2,i=e.height/2,n=Math.floor(e.widthSegments),s=Math.floor(e.heightSegments),a=n+1,o=s+1,l=e.width/n,c=e.height/s,h=[],u=[],d=[],p=[];for(let m=0;m<o;m++){const A=m*c-i;for(let g=0;g<a;g++){const y=g*l-t;u.push(y,-A,0),d.push(0,0,1),p.push(g/n),p.push(1-m/s)}}for(let m=0;m<s;m++)for(let A=0;A<n;A++){const g=A+a*m,y=A+a*(m+1),_=A+1+a*(m+1),v=A+1+a*m;h.push(g,y,v),h.push(y,_,v)}return{indices:h,vertices:u,normals:d,uvs:p}}}class JI extends gr{constructor(e="cylinder",t){super(e),this.defaultParams={radiusTop:1,radiusBottom:1,height:1,radialSegments:32,heightSegments:1,openEnded:!1,thetaStart:0,thetaLength:Math.PI*2},t&&Object.assign(this.defaultParams,t)}_generateTorso(e){const{radiusTop:t,radiusBottom:i,height:n,radialSegments:s,heightSegments:a,thetaStart:o,thetaLength:l,indexArray:c,indices:h,groups:u,vertices:d,normals:p,uvs:m,groupStart:A,halfHeight:g}=e,y=new x,_=new x;let v=0;const b=(i-t)/n;for(let T=0;T<=a;T++){const E=[],M=T/a,S=M*(i-t)+t;for(let w=0;w<=s;w++){const C=w/s,D=C*l+o,O=Math.sin(D),F=Math.cos(D);_.x=S*O,_.y=-M*n+g,_.z=S*F,d.push(_.x,_.y,_.z),y.set(O,b,F).normalize(),p.push(y.x,y.y,y.z),m.push(C,1-M),E.push(e.index++)}c.push(E)}for(let T=0;T<s;T++)for(let E=0;E<a;E++){const M=c[E][T],S=c[E+1][T],w=c[E+1][T+1],C=c[E][T+1];h.push(M,S,C),h.push(S,w,C),v+=6}u.push({start:A,count:v,materialIndex:0}),e.groupStart+=v}_generateCap(e,t){const{radiusTop:i,radiusBottom:n,radialSegments:s,thetaStart:a,thetaLength:o,indices:l,groups:c,vertices:h,normals:u,uvs:d,groupStart:p,halfHeight:m}=e,A=e.index,g=new $,y=new x;let _=0;const v=t===!0?i:n,b=t===!0?1:-1;for(let E=1;E<=s;E++)h.push(0,m*b,0),u.push(0,b,0),d.push(.5,.5),e.index++;const T=e.index;for(let E=0;E<=s;E++){const S=E/s*o+a,w=Math.cos(S),C=Math.sin(S);y.x=v*C,y.y=m*b,y.z=v*w,h.push(y.x,y.y,y.z),u.push(0,b,0),g.x=w*.5+.5,g.y=C*.5*b+.5,d.push(g.x,g.y),e.index++}for(let E=0;E<s;E++){const M=A+E,S=T+E;t===!0?l.push(S,S+1,M):l.push(S+1,S,M),_+=3}c.push({start:p,count:_,materialIndex:t===!0?1:2}),e.groupStart+=_}_generateData(e){let{radialSegments:t,heightSegments:i}=e;t=Math.floor(t),i=Math.floor(i);const n={indices:[],vertices:[],normals:[],uvs:[],numberOfVertices:0,groupStart:0,groups:[],index:0,indexArray:[],halfHeight:e.height/2,...e,radialSegments:t,heightSegments:i};return this._generateTorso(n),e.openEnded===!1&&(e.radiusTop>0&&this._generateCap(n,!0),e.radiusBottom>0&&this._generateCap(n,!1)),n}}const Ki={};Ki.LineCurve={ctor:Xo,vals:{start:"v1",end:"v2"},getUiConfig:r=>[ti(r,"v1","Start Point"),ti(r,"v2","End Point")]},Ki.CubicBezierCurve={ctor:bu,vals:{start:"v0",end:"v3",control1:"v1",control2:"v2"},getUiConfig:r=>[ti(r,"v0","Start Point"),ti(r,"v1","Control Point 1"),ti(r,"v2","Control Point 2"),ti(r,"v3","End Point")]},Ki.QuadraticBezierCurve={ctor:wu,vals:{start:"v0",end:"v2",control1:"v1"},getUiConfig:r=>[ti(r,"v0","Start Point"),ti(r,"v1","Control Point"),ti(r,"v2","End Point")]},Ki.EllipseCurve={ctor:qo,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:r=>[ti(r,"aX","X Center"),ti(r,"aY","Y Center"),ti(r,"xRadius","X Radius"),ti(r,"yRadius","Y Radius"),ti(r,"aStartAngle","Start Angle"),ti(r,"aEndAngle","End Angle"),ti(r,"aClockwise","Clockwise"),ti(r,"aRotation","Rotation")]},Ki.ArcCurve={ctor:hp,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise"},getUiConfig:r=>{const e=ti(r,"xRadius","Radius");if(e){const t=e.onChange;e.onChange=(...i)=>{r.yRadius=r.xRadius,t?.(...i)}}return[ti(r,"aX","X Center"),ti(r,"aY","Y Center"),e,ti(r,"aStartAngle","Start Angle"),ti(r,"aEndAngle","End Angle"),ti(r,"aClockwise","Clockwise")]}},Ki.SplineCurve={ctor:xu,vals:{points:"points"},getUiConfig:r=>[()=>r.points.map((e,t)=>ti(r.points,t.toString(),`Point ${t}`)),{type:"button",label:"Add Point",value:()=>{const e=r.points,t=e[e.length-1]||new $(0,0),i=e[e.length-2]||new $(1,1);e.push(t.clone().add(t.clone().sub(i))),r.points=e,r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame")}}]},Ki.LineCurve3={...Ki.LineCurve,ctor:Yo},Ki.CubicBezierCurve3={...Ki.CubicBezierCurve,ctor:dp},Ki.QuadraticBezierCurve3={...Ki.QuadraticBezierCurve,ctor:Cu},Ki.CatmullRomCurve3={ctor:Oc,vals:{points:"points",closed:"closed",curveType:"curveType",tension:"tension"},getUiConfig:r=>[()=>r.points.map((e,t)=>ti(r.points,t.toString(),`Point ${t}`)),{type:"button",label:"Add Point",value:()=>{const e=r.points,t=e[e.length-1]||new x(0,0,0),i=e[e.length-2]||new x(1,1,0);e.push(t.clone().add(t.clone().sub(i))),r.points=e,r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame")}},ti(r,"closed","Closed Loop"),{type:"dropdown",property:[r,"curveType"],label:"Curve Type",children:["centripetal","chordal","catmullrom"].map(e=>({label:e,value:e}))},ti(r,"tension","Tension")]},Ki.EllipseCurve3D={ctor:yl,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:Ki.EllipseCurve.getUiConfig},Ki.CurvePath={ctor:Su,vals:{},getUiConfig:r=>[()=>r.curves.map((e,t)=>{if(e.uiConfig)return e.uiConfig;const i=e.type,n=Ki[i];if(n){const s=n.getUiConfig(e)||[],a={type:"folder",label:i.replace(/([A-Z])/g," $1").trim(),children:[Jd(e,o=>{r.curves[t]=o,r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame")}),...s,{type:"button",label:"Remove Curve",value:()=>(r.curves.splice(t,1),r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame"),!0)}]};return e.uiConfig=a,a}}),{type:"button",label:"Add Curve",value:()=>{const e=r.type.endsWith("3")?new Yo(new x(0,0,0),new x(1,1,0)):new Xo(new $(0,0),new $(1,1));return r.add(e),r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame"),!0}}]},Ki.CurvePath3={...Ki.CurvePath,ctor:Cm};function Jd(r,e,t=Ki){return{type:"dropdown",label:"Curve Type",children:Object.keys(t).map(i=>({label:i.replace(/([A-Z])/g," $1").trim(),value:i})),getValue:()=>r&&r.type||"LineCurve3",setValue:i=>{const n=r.type?t[r.type]:null,s=t[i];if(!(r&&s&&r.type!==i))return!0;const a=s.ctor;if(!a)return!1;const o=new a;if(Array.isArray(o.points)&&o.points.length===0){const l=o.type.endsWith("3")?new x:new $,c=o.type.endsWith("3")?new x(1,1,1):new $(1,1);o.points.push(l,c)}if(Array.isArray(o.curves)&&o.curves.length===0){const l=o.type.endsWith("3")?new Yo(new x(0,0,0),new x(1,1,0)):new Xo(new $(0,0),new $(1,1));o.curves.push(l)}if(n){const l=Object.entries(n.vals).map(([c,h])=>[c,r[h],s.vals[c]]).filter(([c,h,u])=>h!=null&&!!u);for(const[,c,h]of l){const u=o[h];u!==void 0&&(typeof u=="object"&&typeof u.copy=="function"?o[h].copy(c):Array.isArray(u)&&Array.isArray(c)?o[h]=[...c]:typeof u=="object"&&typeof c=="object"&&c!==null?o[h]={...c}:o[h]=c)}}return e(o),!0}}}function Fg(r,e=Ki){const t=r.type,i=e[t];if(!i)return[];const n={type:"folder",label:t.replace(/([A-Z])/g," $1").trim(),children:i.getUiConfig(r)||[]};return r.uiConfig=n,[n]}class ZI extends gr{constructor(e="tube",t){super(e),this.defaultParams={path:new yl(0,0,1,1,0,2*Math.PI,!1,0),tubularSegments:64,radius:.1,radialSegments:8,closed:!1},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=new Du(e.path,e.tubularSegments,e.radius,e.radialSegments,e.closed),i=t.getAttribute("position"),n=t.getAttribute("normal"),s=t.getAttribute("uv"),o={indices:t.index?Array.from(t.index.array):[],vertices:i,normals:n,uvs:s};return t.dispose(),o}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const n=super.createUiConfig(e).filter(a=>a.label!=="path"),s=a=>{t.path=a,e.userData.__generationParamsUiType="",this.generate(e)};return[Jd(t.path,s),...Fg(t.path),...n]}}function z_(r,e){const t=new ar;switch(r){case"rectangle":{const i=(e.width??1)/2,n=(e.height??1)/2;return t.moveTo(-i,-n),t.lineTo(i,-n),t.lineTo(i,n),t.lineTo(-i,n),t.closePath(),t}case"circle":{const i=e.circleRadius??1,n=e.circleSegments??32;for(let s=0;s<n;s++){const a=s/n*Math.PI*2,o=i*Math.cos(a),l=i*Math.sin(a);s===0?t.moveTo(o,l):t.lineTo(o,l)}return t.closePath(),t}case"polygon":{const i=Math.max(3,e.sides??6),n=e.polygonRadius??1;for(let s=0;s<i;s++){const a=s/i*Math.PI*2-Math.PI/2,o=n*Math.cos(a),l=n*Math.sin(a);s===0?t.moveTo(o,l):t.lineTo(o,l)}return t.closePath(),t}default:throw new Error("Unknown shape preset type: "+r)}}function eP(r){const e=r.getPoints();return e.reverse(),new ar(e)}class tP extends gr{constructor(e="shape",t){super(e),this.defaultParams={shapeType:"rectangle",width:1,height:1,circleRadius:1,circleSegments:32,sides:6,polygonRadius:1,curveSegments:12},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=z_(e.shapeType,e),i=new Pu(t,e.curveSegments);i.computeVertexNormals();const n=i.getAttribute("position"),s=i.getAttribute("normal"),a=i.getAttribute("uv"),l={indices:i.index?Array.from(i.index.array):[],vertices:n,normals:s,uvs:a};return i.dispose(),l}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const i=super.createUiConfig(e);for(const n of i){const s=n.label;s==="width"||s==="height"?n.hidden=()=>t.shapeType!=="rectangle":s==="circleRadius"||s==="circleSegments"?n.hidden=()=>t.shapeType!=="circle":(s==="sides"||s==="polygonRadius")&&(n.hidden=()=>t.shapeType!=="polygon")}return i}}class iP extends gr{constructor(e="tubeShape",t){super(e),this.defaultParams={path:new yl(0,0,2,2,0,2*Math.PI,!1,0),shapeType:"rectangle",width:.5,height:.3,circleRadius:.2,circleSegments:16,sides:6,polygonRadius:.2,shapeSegments:16,tubularSegments:64,closed:!1,shapeScaleX:1,shapeScaleY:1,primary:"shape",materialSplits:""},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=e.shapeType==="custom"&&e.shape?e.shape:z_(e.shapeType,e),i=eP(t),n=new FM(i,e.path,e.shapeSegments,e.tubularSegments,e.closed,new $(e.shapeScaleX,e.shapeScaleY),e.primary);if(e.materialSplits){const h=e.materialSplits.split(",").map(u=>parseFloat(u.trim())).filter(u=>!isNaN(u));h.length>0&&n.createSplits(h)}const s=n.getAttribute("position"),a=n.getAttribute("normal"),o=n.getAttribute("uv"),c={indices:n.index?Array.from(n.index.array):[],vertices:s,normals:a,uvs:o};return n.groups.length>0&&(c.groups=n.groups.map(h=>({start:h.start,count:h.count,materialIndex:h.materialIndex}))),n.dispose(),c}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const n=super.createUiConfig(e).filter(a=>{const o=a.label;return o!=="path"&&o!=="shape"});for(const a of n){const o=a.label;o==="width"||o==="height"?a.hidden=()=>t.shapeType!=="rectangle":o==="circleRadius"||o==="circleSegments"?a.hidden=()=>t.shapeType!=="circle":(o==="sides"||o==="polygonRadius")&&(a.hidden=()=>t.shapeType!=="polygon")}const s=a=>{t.path=a,e.userData.__generationParamsUiType="",this.generate(e)};return[Jd(t.path,s),...Fg(t.path),...n]}}const jh=class jh extends gr{constructor(e="line",t){super(e),this.defaultParams={curve:new Yo(new x(0,0,0),new x(1,1,0)),segments:50,closePath:!1},this.defaultMeshClass=()=>jh.UseMeshLines?u0:fn,this.defaultMaterialClass=()=>jh.UseMeshLines?ji:$n,this.defaultGeometryClass=()=>jh.UseMeshLines?d0:_d,t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=[];let i=e.curve;if(!i&&this.defaultParams.curve&&(i=this.defaultParams.curve),!i)throw new Error("No curve specified for line generation");const n=Math.max(2,e.segments||50),s=e.closePath||!1;i.updateArcLengths();const a=i.getSpacedPoints(n-1);a.length!==n&&console.error(`LineGeometryGenerator: Curve points length (${a.length}) does not match segments (${n}).`);for(const o of a)"z"in o?t.push(o.x,o.y,o.z):t.push(o.x,o.y,0);if(s&&a.length>0){const o=a[0];"z"in o?t.push(o.x,o.y,o.z):t.push(o.x,o.y,0)}return{vertices:t,normals:[],uvs:[],positions:t}}createUiConfig(e){const t=super.createUiConfig(e),i=t.find(o=>o.label==="curve"&&o.type==="folder"),n=e.userData.generationParams?.curve;if(!n)return[];if(n?.uiConfig){const o=i?t.indexOf(i):-1;o>=0?t.splice(o,1,n.uiConfig):t.push(n.uiConfig)}else if(i){const o=Fg(n);if(o.length>0){const l=t.indexOf(i);t.splice(l,1,...o)}}return[Jd(n,o=>{e.userData.generationParams.curve=o,e.userData.__generationParamsUiType="",this.generate(e)}),...t]}};jh.UseMeshLines=!0;let Ng=jh;const pb=class pb extends pt{constructor(){super(...arguments),this.enabled=!0,this.toJSON=void 0,this.generators={plane:new KI("plane"),sphere:new $I("sphere"),box:new YI("box"),circle:new XI("circle"),torus:new qI("torus"),cylinder:new JI("cylinder"),tube:new ZI("tube"),shape:new tP("shape"),tubeShape:new iP("tubeShape"),line:new Ng("line")},this.defaultMeshClass=zm,this.defaultMaterialClass=ai,this.defaultGeometryClass=_d,this._objectAdd=e=>{const t=e.object,i=t?.geometry?.userData?.generationParams?.type;i&&G_(t.geometry,()=>{const n=t.geometry;if(!n)return[];const s=this.generators[i];return s?.createUiConfig?s.createUiConfig(n)??[]:[]})},this._objectRemove=e=>{const t=e.object?.geometry;t?.userData?.generationParams?.type&&BW(t)},this._geometryUpdate=e=>{e.regenerate&&e.geometry?.userData?.generationParams&&this.updateGeometry(e.geometry)},this.uiConfig={type:"folder",label:"Generate Geometry",children:[()=>Object.keys(this.generators).map(e=>({type:"button",uuid:"generate_"+e,label:"Generate "+e,value:async()=>{const t=this.generateObject(e);t.name=e,this._viewer?.scene.addObject(t)}}))]}}generateObject(e,{mesh:t,geometry:i,material:n,...s}={}){const a=this.generators[e];if(!a)throw new Error("Unknown generator type: "+e);let o=t;const l=o?.geometry||i||(a.defaultGeometryClass?new(a.defaultGeometryClass()):new this.defaultGeometryClass),c=o?.material||n||(a.defaultMaterialClass?new(a.defaultMaterialClass()):new this.defaultMaterialClass);return o=o||(a.defaultMeshClass?new(a.defaultMeshClass())(l,c):new this.defaultMeshClass(l,c)),o&&(o.geometry!==l&&(o.geometry=l),o.material!==c&&(o.material=c),a.generate(o.geometry,s),o.name=e,l.name||(l.name="Generated "+Hx(e)),c.name||(c.name="Material for "+l.name),o)}generateGeometry(e,t,i){const n=this.generators[e];if(!n)throw new Error("Unknown generator type: "+e);const s=n.generate(i,t);return s.name="Generated "+e,s}updateGeometry(e,t){if(!e.userData.generationParams?.type)throw new Error("Geometry is not generated");const i=this.generators[e.userData.generationParams.type];if(!i)throw new Error("Unknown generator type: "+e.userData.generationParams.type);i.generate(e,t)}onAdded(e){super.onAdded(e),e.scene.addEventListener("geometryUpdate",this._geometryUpdate),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.forPlugin("Object3DGeneratorPlugin",t=>{t.addObject3DGenerators("geometry-",Object.fromEntries(Object.keys(this.generators).map(i=>[i,n=>{const s=this.generateObject(i,n);return s.name=i,s}])))},t=>{t.removeObject3DGenerators("geometry-")},this)}onRemove(e){e.scene.removeEventListener("geometryUpdate",this._geometryUpdate),e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),super.onRemove(e)}};pb.PluginType="GeometryGeneratorPlugin";let Ph=pb;var LW=Object.defineProperty,OW=Object.getOwnPropertyDescriptor,Co=(r,e,t,i)=>{for(var n=i>1?void 0:i?OW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&LW(e,t,n),n};f.ShapeTubeExtrudePlugin=class extends pt{constructor(){super(...arguments),this.dependencies=[ws,Ph],this.enabled=!0,this.toJSON=void 0,this.shapeSegments=32,this.tubularSegments=32,this.shapeScaleX=1,this.shapeScaleY=1,this.materialSplits="0.3, 0.6",this.horizontalSplits=!0,this.extrudeCircleTube=async()=>{const t=this._viewer?.getPlugin(ws)?.getSelectedObject();if(!t||!t.geometry)return;const i=1,n=new yl(0,0,i,i,0,2*Math.PI,!1,0);this.extrudeObject(t,n)}}extrudeObject(e,t,i=this.shapeSegments,n=this.tubularSegments,s=this.shapeScaleX,a=this.shapeScaleY,o=this.materialSplits,l=this.horizontalSplits){if(!this._viewer)return;if(e.userData._extrudeSource){const m=e.userData._extrudeSource,A=e.parent?.children.find(g=>m===g.uuid);if(!A){console.warn("Could not find extrude source with uuid",m);return}e=A}if(e.userData.extrudedObject){const m=e.userData.extrudedObject,A=e.parent?.children.find(g=>m===g.uuid);A&&A.dispose?.(!0),delete e.userData.extrudedObject}const c=e.geometry;if(!c){console.warn("ShapeTubeExtrudePlugin: No geometry to extrude");return}let h;try{h=f.ShapeTubeExtrudePlugin.ConvertGeometryToFlatShape(c)}catch(m){console.warn("ShapeTubeExtrudePlugin:",typeof m=="string"?m:m?.message);return}const u=this._viewer.getPlugin(Ph);if(!u)return;const d=o?o.split(",").map(m=>parseFloat(m.trim())).filter(m=>!isNaN(m)).join(", "):"",p=u.generateObject("tubeShape",{path:t,shapeType:"custom",shape:h,shapeSegments:i,tubularSegments:n,closed:!0,shapeScaleX:s,shapeScaleY:a,primary:l?"shape":"path",materialSplits:d});p.userData._extrudeSource=e.uuid,p.userData.isExtrudedTube=!0,p.name=e.name+"_extruded",e.visible=!1,e.userData.extrudedObject=p.uuid,e.parent?e.parent.add(p):this._viewer.scene.addObject(p)}static ExtrudeShape(e,t,i,n=32,s=64,a=1,o=1,l="",c=!0){const h=e.getPlugin(Ph);if(h)return h.generateObject("tubeShape",{path:i,shapeType:"custom",shape:t,shapeSegments:n,tubularSegments:s,closed:!0,shapeScaleX:a,shapeScaleY:o,primary:c?"shape":"path",materialSplits:l})}static ConvertGeometryToFlatShape(e,t=!0){if(e.userData.__planarShape)return e.userData.__planarShape;const i=e.attributes.position;if(!i)throw new Error("No position attribute");if(i.count>500)throw new Error("Too many vertices to extrude (max 500)");e.boundingBox||e.computeBoundingBox();const n=e.boundingBox.getSize(new x),s=n.x<.001?"x":n.y<.001?"y":n.z<.001?"z":null;if(!s)throw new Error("Geometry is not axis-aligned planar");let a=[];for(let l=0;l<i.count;l++){const c=new $;s==="x"?c.set(i.getY(l),i.getZ(l)):s==="y"?c.set(i.getX(l),i.getZ(l)):c.set(i.getX(l),i.getY(l)),a.push(c)}if(t){let l=0;for(let c=0;c<a.length;c++)(a[c].x<a[l].x||a[c].x===a[l].x&&a[c].y<a[l].y)&&(l=c);l!==0&&(a=a.slice(l).concat(a.slice(0,l)))}const o=new ar(a);return e.userData.__planarShape=o,o}},f.ShapeTubeExtrudePlugin.PluginType="ShapeTubeExtrudePlugin",Co([Oe("Shape Segments",[1,100],1)],f.ShapeTubeExtrudePlugin.prototype,"shapeSegments",2),Co([Oe("Tube Segments",[1,100],1)],f.ShapeTubeExtrudePlugin.prototype,"tubularSegments",2),Co([Oe("Shape Scale X",[.01,10],.01)],f.ShapeTubeExtrudePlugin.prototype,"shapeScaleX",2),Co([Oe("Shape Scale Y",[.01,10],.01)],f.ShapeTubeExtrudePlugin.prototype,"shapeScaleY",2),Co([Fe("Material Splits")],f.ShapeTubeExtrudePlugin.prototype,"materialSplits",2),Co([ae("Horizontal Splits")],f.ShapeTubeExtrudePlugin.prototype,"horizontalSplits",2),Co([lt("Extrude Circle Tube")],f.ShapeTubeExtrudePlugin.prototype,"extrudeCircleTube",2),f.ShapeTubeExtrudePlugin=Co([gt("Extrude Tube Shapes")],f.ShapeTubeExtrudePlugin);const UW=`
#ifdef HDRi_GROUND_PROJ
float intersectPlane1(const in vec3 r0,const in vec3 rd,const in vec3 n,const in vec3 p0){float t=dot(p0-r0,n)/(dot(n,rd)+1e-6);return t<0. ? 1000. : t;}float intersectSphere1(in vec3 ro,in vec3 rd,in vec3 sph,in float rad){vec3 oc=ro-sph;float b=dot(oc,rd);float c=dot(oc,oc)-rad*rad;float t=b*b-c;return t<0.0 ? t :-b+sqrt(t);}
#define PI_HALF 1.5707963267948966
uniform float worldRadius;uniform float tripodHeight;uniform vec3 originPosition;vec3 hdriProject(){vec3 p=normalize(vWorldDirection);vec3 camPos=cameraPosition;camPos.y-=tripodHeight;float t=intersectSphere1(camPos,p,originPosition,worldRadius);if(t>0.0){float t2=intersectPlane1(camPos,p,vec3(0,-1,0),originPosition+vec3(0.0,-tripodHeight,0.0));p=(camPos+min(t,t2)*p)/worldRadius;/*if(t2<t&&tripodHeight<0.001){float phi=atan(p.z,p.x);float p1=0.4;float l=length(p.xz);p1=(1.-p1*l)/(1.-p1);float theta=sin(l*PI_HALF)*PI_HALF;p.x=sin(theta)*cos(phi)*p1;p.y=-cos(theta);p.z=sin(theta)*sin(phi)*p1;}*/}else p=vec3(0.0,1.0,0.0);return p;}
#endif
`;var FW=Object.defineProperty,NW=Object.getOwnPropertyDescriptor,Dh=(r,e,t,i)=>{for(var n=i>1?void 0:i?NW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&FW(e,t,n),n};f.HDRiGroundPlugin=class extends pt{constructor(e=!1,t=!0){super(),this.enabled=!1,this.worldRadius=100,this.tripodHeight=10,this.originPosition=new x(0,0,0),this.promptOnBackgroundMismatch=!0,this.setDirty=this.setDirty.bind(this),this.enabled=e,this.promptOnBackgroundMismatch=t,this.addEventListener("deserialize",this.setDirty)}setDirty(){if(!this._viewer)return;const e=this._viewer.scene.background;this.enabled&&e!==this._viewer.scene.environment&&e!=="environment"&&(e&&e.isDataTexture?e.mapping=Jr:(this.promptOnBackgroundMismatch?this._viewer.dialog.confirmSync("Background must be same as environment, do you want to change it?"):!0)?this._viewer.scene.background="environment":this.enabled=!1);const t=this._viewer.renderManager.renderer.background.getBoxMesh2()?.material,i=t?.uniforms??Di.backgroundCube.uniforms;i.tripodHeight||(i.tripodHeight={value:1}),i.worldRadius||(i.worldRadius={value:1}),i.originPosition||(i.originPosition={value:new x}),i.tripodHeight.value=this.tripodHeight,i.worldRadius.value=this.worldRadius,i.originPosition.value.copy(this.originPosition),t&&(this.isDisabled()&&t.defines.HDRi_GROUND_PROJ?delete t.defines.HDRi_GROUND_PROJ:this.isDisabled()||(t.defines.HDRi_GROUND_PROJ="1"),t.needsUpdate=!0),this._viewer.setDirty()}onAdded(e){if(super.onAdded(e),this._viewer?.renderManager.webglRenderer?.background.getBoxMesh()&&e.console.error("HDRi Ground Plugin must be added before setting any cube or env map"),!Di.backgroundCube.fragmentShader.includes("#ifdef HDRi_GROUND_PROJ")){const t="void main() {",i=Di.backgroundCube.fragmentShader.split(t);i.length!==2?e.console.error("HDRi Ground Plugin: Could not parse backgroundCube shader"):Di.backgroundCube.fragmentShader=i[0]+`
${UW}
${t}
vec3 worldDirection = 
#ifdef HDRi_GROUND_PROJ
hdriProject()
#else
vWorldDirection
#endif
;
${At(i[1],"vWorldDirection","worldDirection",{replaceAll:!0})}
`}e.scene.addEventListener("environmentChanged",this.setDirty)}},f.HDRiGroundPlugin.PluginType="HDRiGroundPlugin",Dh([z(),de(f.HDRiGroundPlugin.prototype.setDirty),ae("Enabled")],f.HDRiGroundPlugin.prototype,"enabled",2),Dh([z(),de(f.HDRiGroundPlugin.prototype.setDirty),Oe("World Radius",[1,1e3],.01)],f.HDRiGroundPlugin.prototype,"worldRadius",2),Dh([z(),de(f.HDRiGroundPlugin.prototype.setDirty),Oe("Tripod height",[0,50],.01)],f.HDRiGroundPlugin.prototype,"tripodHeight",2),Dh([z(),de(f.HDRiGroundPlugin.prototype.setDirty),gi("Origin Position",void 0,.001,r=>({onChange:r.setDirty}))],f.HDRiGroundPlugin.prototype,"originPosition",2),Dh([z(),de(f.HDRiGroundPlugin.prototype.setDirty)],f.HDRiGroundPlugin.prototype,"promptOnBackgroundMismatch",2),f.HDRiGroundPlugin=Dh([gt("HDRi Ground")],f.HDRiGroundPlugin);var kW=Object.defineProperty,GW=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&kW(e,t,n),n};const V_=(Wh=class extends pt{constructor(e=!0,t=!1){super(),this.enabled=!0,this.helpers=[xI,PI,MI,CI,SI,TI],this.toJSON=null,this.inSceneRoot=!1,this._widgetRoot=new Al,this.refreshObject=i=>{this._createWidget(i)||this._removeWidget(i)},this._viewerListeners={preRender:()=>{this.widgets.forEach(i=>i.preRender&&i.preRender())}},this.widgets=[],this._widgetDisposed=i=>this._unregisterWidget(i.target),this._objectAdd=i=>{const n=i.object;this._createWidget(n)},this._objectRemove=i=>{const n=i.object;this._removeWidget(n)},this.uiConfig={type:"folder",label:"Widgets",children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"]}]},this.enabled=e,this.inSceneRoot=t}setDirty(){this.widgets?.forEach(e=>e.visible=!this.isDisabled()),this._viewer?.setDirty()}onAdded(e){super.onAdded(e),this._widgetRoot.userData.isWidgetRoot=!0,this._widgetRoot.name="Widgets Root",this._modelRoot=this.inSceneRoot?e.scene:e.scene.modelRoot,e.scene.addObject(this._widgetRoot,{addToRoot:!0,autoScale:!1,autoCenter:!1}),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove)}onRemove(e){e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),this.widgets.forEach(t=>t.dispose&&t.dispose()),this.widgets=[],this._widgetRoot.removeFromParent(),this._widgetRoot.clear(),super.onRemove(e)}_registerWidget(e){this.widgets.push(e),e.addEventListener("dispose",this._widgetDisposed)}_unregisterWidget(e){e.removeEventListener("dispose",this._widgetDisposed);const t=this.widgets.indexOf(e);t>=0&&this.widgets.splice(t,1)}_createWidget(e){if(!e||e.assetType==="widget"||e===this._widgetRoot||e.isWidget||e.userData.disableWidgets)return!1;let t=!1,i=!1;if(e.traverseAncestors(a=>{t=t||a===this._widgetRoot||!!a.isWidget||a.assetType==="widget"||!!a.userData.disableWidgets,i=i||a===this._modelRoot}),t||!i)return!1;const n=this.widgets.find(a=>a.object===e);if(n)return n.update&&n.update(),!0;const s=this.helpers.filter(a=>a.Check(e));for(const a of s){const o=a.Create(e);o.visible=!this.isDisabled(),this._widgetRoot.add(o),this._registerWidget(o)}return!0}_removeWidget(e){if(!e)return;const t=this.widgets.filter(i=>i.object===e);for(const i of t)i.dispose&&i.dispose(!0),i.parent&&i.removeFromParent(),this._unregisterWidget(i)}},Wh.PluginType="Object3DWidgetsPlugin",Wh);GW([de(V_.prototype.setDirty)],V_.prototype,"enabled");let zW=V_;var VW=Object.defineProperty,HW=Object.getOwnPropertyDescriptor,H_=(r,e,t,i)=>{for(var n=i>1?void 0:i?HW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&VW(e,t,n),n};f.Object3DGeneratorPlugin=class extends pt{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this._selectedType="",this.generators={"object-empty":(e={})=>{const t=new BM;return e.position?t.position.copy(e.position):t.position.set(0,0,0),t.name=e.name??"New Object",t},"object-group":(e={})=>{const t=new Al;return e.position?t.position.copy(e.position):t.position.set(0,0,0),t.name=e.name??"New Object",t},"camera-perspective":(e={})=>{const t=new th(e.controlsMode??"",this._viewer?.canvas,e.autoAspect,e.fov,e.aspect);return e.position?t.position.copy(e.position):t.position.set(0,0,5),e.target?t.target.copy(e.target):t.target.set(0,0,0),t.autoLookAtTarget=e.autoLookAtTarget??!0,t.setDirty(),t.name=e.name??"Perspective Camera",t},"camera-orthographic":(e={})=>{const t=new yd(e.controlsMode??"",this._viewer?.canvas,e.autoAspect,e.frustumSize);return e.position?t.position.copy(e.position):t.position.set(0,0,5),e.target?t.target.copy(e.target):t.target.set(0,0,0),t.autoLookAtTarget=e.autoLookAtTarget??!0,t.setDirty(),t.name=e.name??"Orthographic Camera",t},"light-directional":(e={})=>{const t=new Qm(e.color??16711680,e.intensity??3);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.lookAt(e.target??new x(0,0,0)),t.name="Directional Light",t},"light-ambient":(e={})=>{const t=new vl(e.color??16777215,e.intensity??1);return t.name="Ambient Light",t},"light-point":(e={})=>{const t=new jm(e.color??16711680,e.intensity??3);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.name="Point Light",t},"light-spot":(e={})=>{const t=new Wm(e.color??16711680,e.intensity??3);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.lookAt(e.target??new x(0,0,0)),t.name="Spot Light",t},"light-hemisphere":(e={})=>{const t=new Ca(e.color??11184895,5592131,e.intensity??1);return t.name="Hemisphere Light",t},"light-rect-area":(e={})=>{const t=new Nr(e.color??255,e.intensity??3,2,2);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.lookAt(e.target??new x(0,0,0)),t.name="Rect Area Light",t}},this._selectedType=Object.keys(this.generators)[0]}generate(e,t,i=!0,n=!0,s=!0){if(!this._viewer)throw new Error("No viewer");const a=this.generators[e??this._selectedType]?.(t);if(i&&a){const o={redo:()=>this._viewer?.scene.addObject(a),undo:()=>a.dispose?a.dispose(!0):a.removeFromParent()};s&&this._viewer?.getPlugin("UndoManagerPlugin")?.undoManager?.record(o),o.redo(),n&&a.dispatchEvent({type:"select",value:a,object:a,ui:!0,bubbleToParent:!0,trackUndo:!1})}return a||void 0}removeObject3DGenerators(e,t=!0){return this.generators=Object.fromEntries(Object.entries(this.generators).filter(([i,n])=>!i.startsWith(e))),t&&this.uiConfig?.uiRefresh?.(!0),this}removeObject3DGenerator(e,t=!0){return delete this.generators[e],t&&this.uiConfig?.uiRefresh?.(!0),this}addObject3DGenerators(e,t,i=!0){this.removeObject3DGenerators(e,!1),Object.entries(t).forEach(([n,s])=>{this.generators[e+n]=s}),i&&this.uiConfig?.uiRefresh?.(!0)}addObject3DGenerator(e,t,i=!0){this.removeObject3DGenerator(e,!1),this.generators[e]=t,i&&this.uiConfig?.uiRefresh?.(!0)}},f.Object3DGeneratorPlugin.PluginType="Object3DGeneratorPlugin",H_([Oi("Type",void 0,r=>({children:[()=>Object.keys(r.generators).map(e=>({label:e}))]}))],f.Object3DGeneratorPlugin.prototype,"_selectedType",2),H_([lt("Generate",{sendArgs:!1})],f.Object3DGeneratorPlugin.prototype,"generate",1),f.Object3DGeneratorPlugin=H_([Aa("Generate Scene Objects")],f.Object3DGeneratorPlugin);var QW=Object.defineProperty,jW=Object.getOwnPropertyDescriptor,Rh=(r,e,t,i)=>{for(var n=i>1?void 0:i?jW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&QW(e,t,n),n};f.ContactShadowGroundPlugin=class extends f.BaseGroundPlugin{constructor(){super(),this.contactShadows=!0,this.shadowScale=1,this.shadowHeight=5,this.blurAmount=1,this.mapMode="aoMap",this.shadowCamera=new Mr(-1,1,1,-1,.001,this.shadowHeight),this._depthTex=null,this._refreshShadowCameraFrustum=this._refreshShadowCameraFrustum.bind(this),this.refresh=this.refresh.bind(this)}onAdded(e){const t=e.renderManager.createTarget({type:Wt,format:Kt,colorSpace:si,size:{width:512,height:512},generateMipmaps:!1,depthBuffer:!0,minFilter:st,magFilter:st});t.texture.name="groundContactDepthTexture";const i=new xc({depthPacking:xA,transparent:!1,blending:gn});i.opacity=-1,i.onBeforeCompile=n=>{n.fragmentShader=At(n.fragmentShader,"gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( opacity > 0. ? vec3( 1.0 - fragCoordZ ) : vec3( fragCoordZ ), 1.0 );")},this._depthPass=new f.GBufferRenderPass("contactShadowGround",t,i,new se(1,1,1),1),this._blurHelper=new KS(e),super.onAdded(e)}onRemove(e){const t=it(this._depthPass?.target);return t&&this._viewer?.renderManager.disposeTarget(t),this._depthPass?.dispose(),this._depthPass=void 0,this._blurHelper?.dispose(),this._blurHelper=void 0,super.onRemove(e)}_postFrame(){super._postFrame(),this._viewer}_preRender(){if(super._preRender(),!this._viewer||!this._depthPass||!this._blurHelper||!this.contactShadows||!this.visible)return;this._depthPass.scene=this._viewer.scene,this._depthPass.camera=this.shadowCamera,this._depthPass.render(this._viewer.renderManager.renderer,null);const e=it(this._depthPass.target);if(!e)return;const t=this._viewer.renderManager.getTempTarget({type:Wt,format:Kt,colorSpace:si,size:{width:1024,height:1024},generateMipmaps:!1,depthBuffer:!1,minFilter:st,magFilter:st});this._blurHelper.blur(e.texture,e,t,this.blurAmount/256),this._blurHelper.blur(e.texture,e,t,.4*this.blurAmount/256),this._viewer.renderManager.releaseTempTarget(t)}_refreshTransform(){return!super._refreshTransform()||!this._mesh||!this._viewer?!1:(this.shadowCamera.position.copy(this._mesh.getWorldPosition(new x)),this.shadowCamera.setRotationFromEuler(new Tt(Math.PI/2,0,0)),this.shadowCamera.updateMatrixWorld(),this._refreshShadowCameraFrustum(),this._mesh.scale.y=-this.size,!0)}_refreshShadowCameraFrustum(){this.shadowCamera&&(this.shadowCamera.left=-this.size/(2*this.shadowScale),this.shadowCamera.right=this.size/(2*this.shadowScale),this.shadowCamera.top=this.size/(2*this.shadowScale),this.shadowCamera.bottom=-this.size/(2*this.shadowScale),this.shadowCamera.far=this.shadowHeight,this.shadowCamera.updateProjectionMatrix(),this._setDirty())}_setDirty(){this._viewer?.setDirty()}_removeMaterial(){this._material&&(this._material.alphaMap=null,this._material.aoMap=null,this._material.map=null,this._material.userData.ssaoDisabled&&delete this._material.userData.ssaoDisabled,this._material.userData.ssreflDisabled&&delete this._material.userData.ssreflDisabled,this._material.userData.ssreflNonPhysical&&delete this._material.userData.ssreflNonPhysical,super._removeMaterial())}refresh(){this._viewer&&(this.contactShadows?this._depthTex=it(this._depthPass?.target)?.texture||null:(this._material?.alphaMap===this._depthTex&&(this._material.alphaMap=null,this._material.setDirty()),this._material?.aoMap===this._depthTex&&(this._material.aoMap=null,this._material.setDirty()),this._material?.map===this._depthTex&&(this._material.map=null,this._material.setDirty()),this._material?.userData.__csgpParamsSet&&(delete this._material.userData.__csgpParamsSet,delete this._material.userData.ssaoDisabled,delete this._material.userData.ssreflDisabled,delete this._material.userData.ssreflNonPhysical),this._depthTex=null),super.refresh())}_createMaterial(e){const t=super._createMaterial(e);return t.roughness=1,t.metalness=0,t.color.set(16777215),t.transparent=!0,t}_refreshMaterial(){if(!this._viewer)return!1;const e=super._refreshMaterial();return this._material&&this.contactShadows&&(this._material.userData.ssaoDisabled=this.mapMode==="aoMap",this._material.userData.ssreflDisabled=this.mapMode==="alphaMap",this._material.userData.ssreflNonPhysical=!1,this._material.userData.__csgpParamsSet=!0,this._material.alphaMap===this._depthTex&&(this._material.alphaMap=null),this._material.aoMap===this._depthTex&&(this._material.aoMap=null),this._material.map===this._depthTex&&(this._material.map=null),this._material[this.mapMode]=this._depthTex,this._material.setDirty(),this._depthPass&&(this._depthPass.clearColor.set(this.mapMode==="aoMap"?new se(1,1,1):new se(0,0,0)),this._depthPass.clearAlpha=this.mapMode==="aoMap"?1:0,this._depthPass.overrideMaterial.opacity=this.mapMode==="aoMap"?-1:1)),e}},f.ContactShadowGroundPlugin.PluginType="ContactShadowGroundPlugin",Rh([ae("Contact Shadows"),de(f.ContactShadowGroundPlugin.prototype.refresh),z()],f.ContactShadowGroundPlugin.prototype,"contactShadows",2),Rh([Oe("Shadow Scale",[0,2]),z(),de(f.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],f.ContactShadowGroundPlugin.prototype,"shadowScale",2),Rh([Oe("Shadow Height",[0,20]),z(),de(f.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],f.ContactShadowGroundPlugin.prototype,"shadowHeight",2),Rh([Oe("Blur Amount",[0,10]),z(),de(f.ContactShadowGroundPlugin.prototype._setDirty)],f.ContactShadowGroundPlugin.prototype,"blurAmount",2),Rh([de(f.ContactShadowGroundPlugin.prototype._refreshMaterial),Oi("Map Mode",["aoMap","map","alphaMap"]),z()],f.ContactShadowGroundPlugin.prototype,"mapMode",2),f.ContactShadowGroundPlugin=Rh([Aa("Ground Plane (Contact Shadows)")],f.ContactShadowGroundPlugin);var WW=Object.defineProperty,qW=Object.getOwnPropertyDescriptor,Q_=(r,e,t,i)=>{for(var n=i>1?void 0:i?qW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&WW(e,t,n),n};const mb=class mb extends pt{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this.simplifyFactor=.5}get initialized(){return!0}async initialize(){}onAdded(e){super.onAdded(e),this._pickingPlugin=e.getPlugin(ws)}simplifyGeometries(e,t){if(!e){const n=this._pickingPlugin?.getSelectedObject();if(!n?.isObject3D)return;const s=[];if(n?.traverse(a=>{a.geometry&&!s.includes(a.geometry)&&s.push(a.geometry)}),e=s,!e||!e.length)return}Array.isArray(e)||(e=[e]);const i=[];for(const n of e)i.push(this.simplifyGeometry(n,t));return i}simplifyGeometry(e,{factor:t,count:i,replace:n=!0,disposeOnReplace:s=!1}={}){if(!e&&(e=this._pickingPlugin?.getSelectedObject()?.geometry,!e))return;if(!e.attributes.position)return this._viewer?.console.error("SimplifyModifierPlugin: Geometry does not have position attribute",e),e;t=t||this.simplifyFactor,i=i||e.attributes.position.count*t,e.boundingBox||e.computeBoundingBox();const a=this._simplify(e,i);a.computeBoundingBox(),a.computeBoundingSphere(),a.computeVertexNormals();const o=a.boundingBox,l=o.getSize(new x);if(!isFinite(l.x)||!isFinite(l.y)||!isFinite(l.z))return this._viewer?.console.error("SimplifyModifierPlugin: Unable to simplify",e,a,l),e;const c=e.boundingBox,h=c.getSize(new x),u=l.clone().sub(h),d=u.clone().divide(h);if(d.lengthSq()>.001&&console.warn("Simplify",e,a,o,c,l,h,u,d),!n)return a;const p=e.appliedMeshes;if(!p)return console.error("No meshes found for geometry, cannot replace",e),a;for(const m of p)m.geometry=a;return s&&e.dispose(!0),a}async simplifyAll(e,t){if(!e&&this._viewer&&(e=this._viewer.scene.modelRoot),!e){console.error("SimplifyModifierPlugin: No root found");return}if(!this.initialized&&(await this.initialize(),!this.initialized)){this._viewer?.console.error("SimplifyModifierPlugin cannot be initialized");return}const i=[];if(e.traverse(n=>{n.geometry&&!i.includes(n.geometry)&&i.push(n.geometry)}),!i.length){console.error("SimplifyModifierPlugin: No geometries found");return}return this.simplifyGeometries(i,t)}async simplifySelected(){if(!this._viewer)return;if(!this.initialized&&(await this.initialize(),!this.initialized)){await this._viewer.dialog.alert("Simplify: SimplifyModifierPlugin cannot be initialized");return}const e=this._pickingPlugin?.getSelectedObject();if(!e?.isObject3D){await this._viewer.dialog.alert("Simplify: No Object Selected");return}let t=!1;e.geometry?e.children.length===0&&(t=!0):t=!0,t||await this._viewer.dialog.confirm("Simplify: Simplify all in hierarchy?")&&(t=!0),t?this.simplifyGeometries():this.simplifyGeometry(e.geometry)}};mb.PluginType="SimplifyModifierPlugin";let Ll=mb;Q_([Oe("Simplify Factor",[0,1])],Ll.prototype,"simplifyFactor",2),Q_([lt("Simplify All",{sendArgs:!1})],Ll.prototype,"simplifyAll",1),Q_([lt("Simplify Selected")],Ll.prototype,"simplifySelected",1);var XW=Object.defineProperty,YW=Object.getOwnPropertyDescriptor,j_=(r,e,t,i)=>{for(var n=i>1?void 0:i?YW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&XW(e,t,n),n};f.MeshOptSimplifyModifierPlugin=class extends Ll{constructor(e=!0,t=document.head){super(),this.rootNode=t,this._initializing=void 0,this.errorThreshold=.5,this.lockBorder=!1,e&&this.initialize()}get initialized(){return!!window.MeshoptSimplifier}onAdded(e){super.onAdded(e)}async initialize(){if(this.initialized)return;if(this._initializing)return await this._initializing;const e=document.createElement("script");e.type="module";const t=Math.random().toString(36).substring(7);return e.innerHTML=`
import { MeshoptSimplifier } from ${JSON.stringify(f.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL)};
MeshoptSimplifier.ready.then(() => {
window.MeshoptSimplifier = MeshoptSimplifier;
window.dispatchEvent(new CustomEvent('${t}'))
});
`,this._initializing=new Promise(i=>{window.addEventListener(t,()=>i(),{once:!0}),this.rootNode.appendChild(e),this._script=e}),await this._initializing}dispose(){this._script&&(this._script.remove(),delete window.MeshoptSimplifier),this._script=void 0}_simplify(e,t){if(!this.initialized)throw new Error("MeshOptSimplifyModifierPlugin not initialized");e.index?e=e.clone():e=Cv(e);const i=e.index.array,n=e.attributes.position.array,s=t/e.attributes.position.count,a=3*Math.floor(s*i.length/3),[o,l]=window.MeshoptSimplifier.simplify(i,n,3,a,this.errorThreshold,this.lockBorder?["LockBorder"]:[]);return console.log("srcCount",i.length/3,"destCount",o.length/3),l&&console.warn("Simplify error",l),e.setIndex(new Xe(new Uint32Array(o),1)),ri.upgradeGeometry.call(e.toNonIndexed())}},f.MeshOptSimplifyModifierPlugin.PluginType="MeshOptSimplifyModifierPlugin",f.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_simplifier.module.js",j_([Lt()],f.MeshOptSimplifyModifierPlugin.prototype,"errorThreshold",2),j_([ae()],f.MeshOptSimplifyModifierPlugin.prototype,"lockBorder",2),f.MeshOptSimplifyModifierPlugin=j_([gt("Simplify Modifier (meshopt)")],f.MeshOptSimplifyModifierPlugin);const $W=r=>{const e=[],t=new Set;for(const i of r){let n=i,s=0;for(;t.has(n);)n=i+"."+ ++s;t.add(n),e.push(n)}return e},KW=(r,e)=>{const t={};for(const i of r.mappings)for(const n of i.variants)t[e[n]]={material:null,gltfMaterialIndex:i.material};return t},JW=r=>r.material!==void 0&&r.userData&&r.userData._variantMaterials,Bh="KHR_materials_variants";class ZW{constructor(e){this.parser=e,this.name=Bh}async afterRoot(e){const t=this.parser,i=t.json;if(!i.extensions||!i.extensions[this.name])return;const s=i.extensions[this.name].variants||[],a=$W(s.map(l=>l.name));for(const l of e.scenes)l.traverse(c=>{const h=t.associations.get(c);if(!h||h.meshes===void 0||h.primitives===void 0)return;const p=i.meshes[h.meshes].primitives[h.primitives].extensions;!p||!p[this.name]||(c.userData._variantMaterials=KW(p[this.name],a))});const o=async l=>{const c=l.material,h=l.userData._variantMaterials,u=[];for(const d in h){const p=h[d];if(p.material)continue;const m=p.gltfMaterialIndex;u.push(t.getDependency("material",m).then(A=>{l.material=A,t.assignFinalMaterial(l),h[d].material=l.material}))}return Promise.all(u).then(()=>{l.material=c})};await Promise.all(e.scenes.map(async l=>{const c=[];return l.traverse(h=>JW(h)&&c.push(o(h))),l.userData.__importData||(l.userData.__importData={}),l.userData.__importData[Bh]={names:a},Promise.all(c)}))}}const nP=r=>r.material!==void 0&&r.userData&&r.userData._variantMaterials&&!!Object.values(r.userData._variantMaterials).filter(e=>kg(e?.material)),kg=r=>r&&r.isMaterial&&!Array.isArray(r);class e8{constructor(e){this.writer=e,this.name=Bh,this.variantNames=[]}beforeParse(e){const t=new Set;for(const i of e)i.traverse(n=>{if(!nP(n))return;const s=n.userData._variantMaterials;for(const a in s){const o=s[a];kg(o.material)&&t.add(a)}});t.forEach(i=>this.variantNames.push(i))}writeMesh(e,t){if(!nP(e))return;const i=e.userData,n=i._variantMaterials,s={};for(const l in n){const c=n[l].material;if(!kg(c))continue;const h=this.variantNames.indexOf(l),u=this.writer.processMaterial(c);s[u]||(s[u]={material:u,variants:[]}),s[u].variants.push(h)}const a=Object.values(s).map(l=>l.variants.sort((c,h)=>c-h)&&l).sort((l,c)=>l.material-c.material);if(a.length===0)return;const o=kg(i._originalMaterial)?this.writer.processMaterial(i._originalMaterial)??-1:-1;for(const l of t.primitives)o>=0&&(l.material=o),l.extensions=l.extensions||{},l.extensions[this.name]={mappings:a}}afterParse(e){if(this.variantNames.length===0)return;const t=this.writer.json;t.extensions=t.extensions||{};const i=this.variantNames.map(n=>({name:n}));t.extensions[this.name]={variants:i},this.writer.extensionsUsed[this.name]=!0}}function t8(r){return new e8(r)}var i8=Object.defineProperty,sP=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&i8(e,t,n),n};const Gg=(qh=class extends pt{constructor(){super(),this.enabled=!0,this.variants={},this.selectedVariant="",this.applyFirstVariantOnLoad=!0,this._objectAdded=e=>{const t=e.object;t?.isObject3D&&this._viewer&&(t.traverse(i=>{if(i.userData._variantMaterials)for(const a of Object.values(i.userData._variantMaterials))a?.material&&(a.material=this._viewer?.materialManager.convertToIMaterial(a.material,{})||a.material);const n=i.userData?.__importData?.[Bh];if(!n)return;const s=n.names||[];for(const a of s)this.variants[a]||(this.variants[a]=[]),this.variants[a].push(i);delete i.userData.__importData[Bh]}),!this.selectedVariant&&this.applyFirstVariantOnLoad&&(this.selectedVariant=Object.keys(this.variants)[0]||""),this.uiConfig.uiRefresh?.())},this.uiConfig={type:"folder",label:"KHR Material Variants",children:[()=>({children:[null,...Object.keys(this.variants)].map(e=>e?{label:e}:{label:"none",value:""}),type:"dropdown",label:"Variant",property:[this,"selectedVariant"]})]}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._objectAdded),e.assetManager.registerGltfExtension(rP)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._objectAdded),e.assetManager.unregisterGltfExtension(rP.name),this.variants={},super.onRemove(e)}_variantChanged(){this.applyVariant(this.selectedVariant||"",!0)}applyVariant(e,t=!1,i,n=!0){if(!t&&!i&&this.selectedVariant===e||!e)return;i||(this.selectedVariant=e);const s=i?Array.isArray(i)?i:[i]:e?this.variants[e]||[]:Object.values(this.variants).flat();for(const a of s){const o=new Set,l=c=>{if(!c.userData._variantMaterials||o.has(c))return;const h=e?c.userData._variantMaterials[e]?.material:c.userData._originalMaterial;h&&(c.userData._originalMaterial||(c.userData._originalMaterial=c.material),c.material=h),o.add(c)};n?a.traverse(l):l(a)}}},qh.PluginType="GLTFKHRMaterialVariantsPlugin",qh);sP([de(Gg.prototype._variantChanged),z()],Gg.prototype,"selectedVariant"),sP([z()],Gg.prototype,"applyFirstVariantOnLoad");let n8=Gg;const rP={name:Bh,import:r=>new ZW(r),export:t8};var s8=Object.getOwnPropertyDescriptor,r8=(r,e,t,i)=>{for(var n=i>1?void 0:i?s8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(n)||n);return n};f.TailwindCSSCDNPlugin=class extends pt{constructor(){super(...arguments),this.enabled=!0,this._tailwindScript=null,this.toJSON=null}async onAdded(e){super.onAdded(e),this._tailwindScript=document.createElement("script"),this._tailwindScript.src=f.TailwindCSSCDNPlugin.CDN_URL,this._tailwindScript.type="text/javascript",document.head.appendChild(this._tailwindScript)}onRemove(e){this._tailwindScript&&this._tailwindScript.parentNode&&(this._tailwindScript.parentNode.removeChild(this._tailwindScript),this._tailwindScript=null),super.onRemove(e)}},f.TailwindCSSCDNPlugin.PluginType="TailwindCDNPlugin",f.TailwindCSSCDNPlugin.CDN_URL="https://cdn.tailwindcss.com",f.TailwindCSSCDNPlugin=r8([gt("Tailwind CSS")],f.TailwindCSSCDNPlugin);const gb=class gb extends pt{constructor(){super(),this.enabled=!0,this.plugins=new Map,this._path="./TestPlugin.ts",this.uiConfig={type:"folder",label:"Viewer Scripts",expanded:!0,children:[{type:"input",label:"Path",property:[this,"_path"]},{type:"button",label:"Load Plugin",value:async()=>{await this.loadPlugin(this._path),this.uiConfig.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Unload Plugin",value:async()=>{await this.unloadPlugin(this._path),this.uiConfig.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Refresh UI",value:async()=>{this.uiConfig.uiRefresh?.(!0,"postFrame")}},{type:"folder",label:"Loaded Plugins",expanded:!0,children:[()=>[...this.plugins.values()].map(e=>this._viewer?.getPlugin(e)?.uiConfig)]}]}}onAdded(e){super.onAdded(e)}async loadPlugin(e){const t=this._viewer;if(!t)throw new Error("Plugin not added to viewer.");typeof e=="object"&&typeof e.then=="function"&&(e=await e),e=e;const i=typeof e=="string"?e:e.__tpPluginPath||"";if(i?.length&&this.plugins.has(i))throw new Error("Plugin already loaded: "+i);const n=typeof e=="object"?e:typeof i=="string"&&i?await import(i+"?t="+Date.now()):null;if(!n)throw new Error("Could not find/load module: "+i);const s=n.default||Object.values(n)[0];if(!s)throw new Error("No plugin found in module: "+i);if(typeof s!="function")throw new Error("Plugin is not a class or function in module: "+e);if(!(s.prototype&&s.prototype instanceof Zc))throw new Error("Plugin is not a subclass of AViewerPlugin in module: "+e);const a=s.PluginType;if(console.log(a),console.log(n),t.getPlugin(a))throw new Error("Plugin of type "+a+" already added to viewer");return i?.length&&this.plugins.set(i,s),await t.addPlugin(s)}async unloadPlugin(e){const t=this._viewer;if(!t)throw new Error("Plugin not added to viewer.");const i=this.plugins.get(e);if(!i)throw new Error("Plugin not loaded: "+e);const n=t.getPlugin(i);if(!n)throw new Error("Plugin not found in viewer: "+e);await t.removePlugin(n),this.plugins.delete(e)}};gb.PluginType="DynamicImportPlugin";let W_=gb;const a8={handleHotUpdate({server:r,modules:e,timestamp:t}){const i=new Set,n=[];for(const s of e)console.log(s.id,s.url),s.url.endsWith(".plugin.ts")?(r.moduleGraph.invalidateModule(s,i,t,!0),r.ws.send({type:"custom",event:"custom-tp-plugin-update",data:{url:s.url,id:s.id}})):n.push(s);return n},transform(r,e){if(e.endsWith(".plugin.ts")){const t=`
export const __tpPluginPath = "${e}";
`;return r+t}}},Ol={copy_position:{defaultProps:{axis:["x","y","z"],invert:[]},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{axis:n=["x","y","z"],invert:s=[]}=t,a=e.getWorldPosition(new x);let o=!1,l=!0;return n.forEach(c=>{s.includes(c)&&(a[c]*=-1);const h=r.position[c];r.position[c]=a[c]*i+h*(1-i),o=o||Math.abs(r.position[c]-h)>1e-5,l=l&&Math.abs(r.position[c]-h)<1e-5}),{changed:o,end:l,change:"position"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="transform"}},copy_rotation:{defaultProps:{axis:["x","y","z"],invert:[],order:void 0},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{axis:n=["x","y","z"],invert:s=[]}=t;let a=t.order;const o=new Tt().copy(r.rotation);a||(a=o.order),o.order=a;const l=new Qe;e.getWorldQuaternion(l);const c=new Tt().setFromQuaternion(l,a);let h=!1,u=!0;return n.forEach(d=>{let p=c[d];s.includes(d)&&(p*=-1);const m=r.rotation[d],A=p*i+m*(1-i);o[d]=A,h=h||Math.abs(A-m)>1e-5,u=u&&Math.abs(A-m)<1e-5}),r.rotation.copy(o),{changed:h,end:u,change:"rotation"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="rotation"||t==="quaternion"||t==="transform"}},copy_scale:{defaultProps:{axis:["x","y","z"]},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{axis:n=["x","y","z"],uniform:s=!1}=t,a=new x;e.getWorldScale(a);const o=r.scale.clone();let l=0;if(n.forEach(u=>{const d=a[u]*i+o[u]*(1-i);r.scale[u]=d,l=l+d}),s){const u=l/n.length;r.scale.set(u,u,u)}const c=!o.equals(r.scale),h=o.distanceTo(r.scale)<1e-5;return{changed:c,end:h,change:"scale"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="scale"||t==="transform"}},copy_transforms:{defaultProps:{},update:(r,e,t,i)=>{if(!e)return{changed:!1};const n=new pe;e.updateMatrixWorld(),n.copy(e.matrixWorld);const s=new x().copy(r.position),a=new Qe().copy(r.quaternion),o=new x().copy(r.scale),l=new x,c=new Qe,h=new x;n.decompose(l,c,h),r.position.lerpVectors(s,l,i),r.quaternion.slerpQuaternions(a,c,i),r.scale.lerpVectors(o,h,i);const u=!s.equals(r.position)||!a.equals(r.quaternion)||!o.equals(r.scale),d=s.distanceTo(r.position)<1e-5&&a.angleTo(r.quaternion)<1e-5&&o.distanceTo(r.scale)<1e-5;return{changed:u,end:d,change:"transform"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="rotation"||t==="quaternion"||t==="scale"||t==="transform"}},follow_path:{defaultProps:{offset:0,followCurve:!1},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{offset:n=0,followCurve:s=!1}=t;if(!e.geometry)return{changed:!1};const a=e.geometry,o=a.getPositions?a.getPositions():a.attributes?.position?.array,l=o8(o,n);if(!l)return{changed:!1};const{targetPos:c,direction:h}=l,u=e.localToWorld(c.clone()),d=h?.lengthSq()>0?e.localToWorld(h.clone().add(c)).sub(u).normalize():null,p=new x().copy(r.position),m=new Qe().copy(r.quaternion);r.position.copy(u);let A=!1;if(s&&d){const v=u.clone().add(d);if(r.lookAt(v),i!==1){const b=r.quaternion.clone();r.quaternion.slerpQuaternions(m,b,i)}A=!m.equals(r.quaternion)}i!==1&&r.position.lerpVectors(p,u,i);const y=!p.equals(r.position)||A,_=p.distanceTo(r.position)<1e-5&&(!A||m.angleTo(r.quaternion)<1e-5);return{changed:y,end:_,change:A?"transform":"position"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="transform"||t==="geometry"}},look_at:{defaultProps:{upAxis:"y"},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{upAxis:n="y"}=t,a=e.getWorldPosition(new x).clone().sub(r.position).normalize(),o=new x(0,1,0);n==="x"?o.set(1,0,0):n==="-x"?o.set(-1,0,0):n==="y"?o.set(0,1,0):n==="-y"?o.set(0,-1,0):n==="z"?o.set(0,0,1):n==="-z"&&o.set(0,0,-1);const l=new x().crossVectors(o,a).normalize();o.crossVectors(a,l).normalize();const c=new pe;c.makeBasis(l,o,a);const h=new Qe().setFromRotationMatrix(c);r.quaternion.slerp(h,i);const u=!r.quaternion.equals(h),d=r.quaternion.angleTo(h)<1e-5;return{changed:u,end:d,change:"rotation"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="rotation"||t==="quaternion"||t==="scale"||t==="transform"}}};function o8(r,e){if(!r)return null;const t=r.length/3;if(t<2)return null;const i=[];let n=0;for(let b=0;b<t-1;b++){const T=r[b*3],E=r[b*3+1],M=r[b*3+2],S=r[(b+1)*3],w=r[(b+1)*3+1],C=r[(b+1)*3+2],D=Math.sqrt((S-T)**2+(w-E)**2+(C-M)**2);i.push(D),n+=D}if(n===0)return null;const a=Math.max(0,Math.min(1,e))*n;let o=0,l=0,c=0;for(let b=0;b<i.length;b++){if(o+i[b]>=a){l=b,c=(a-o)/i[b];break}o+=i[b]}const h=l*3,u=(l+1)*3,d=r[h],p=r[h+1],m=r[h+2],A=r[u],g=r[u+1],y=r[u+2],_=new x(d+(A-d)*c,p+(g-p)*c,m+(y-m)*c),v=new x(A-d,g-p,y-m);return v.normalize(),{targetPos:_,direction:v}}var l8=Object.defineProperty,c8=Object.getOwnPropertyDescriptor,xo=(r,e,t,i)=>{for(var n=i>1?void 0:i?c8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&l8(e,t,n),n};f.ObjectConstraintsPlugin=class extends pt{constructor(e=!0){super(),this.enabled=!0,this.dependencies=[],this._objectAdd=t=>{const i=t.object;i&&(i.isWidget||(Array.isArray(i.userData.constraints)&&i.userData.constraints.forEach(n=>this._registerConstraint(n,i)),this._setupUiConfig(i),this._constraints.keys().forEach(n=>{n?.target===i.uuid&&this._refreshConstraint(n,i)})))},this._objectRemove=t=>{const i=t.object;i&&(Array.isArray(i.userData.constraints)&&i.userData.constraints.forEach(n=>this._unregisterConstraint(n,i)),this._cleanUpUiConfig(i),this._constraintTargets.get(i)?.forEach(n=>this._refreshConstraint(n,null)))},this._constraints=new Map,this._constraintTargets=new Map,this._constraintObjects=new Map,this._objectUpdate=t=>{this._constraintTargets.get(t.object)?.forEach(i=>{i.setDirty(t,!0)}),this._constraintObjects.get(t.object)?.forEach(i=>{i.setDirty(t,!1)})},this._viewerListeners={preFrame:()=>{if(this.isDisabled()||this._viewer?.timeline.running&&this._viewer.timeline.delta===0)return;this._constraints.keys().filter(i=>i.needsUpdate).forEach(i=>{const n=this._constraints.get(i);n&&i.update(n)})}},this.enabled=e}addConstraint(e,t,i){const n=typeof t=="string"?new f.ObjectConstraint(t):t||new f.ObjectConstraint;return e.userData.constraints||(e.userData.constraints=[]),i&&(typeof i=="string"?n.target=i:n.target=i.uuid),e.userData.constraints.includes(n)||(e.userData.constraints.push(n),this._registerConstraint(n,e),e.setDirty&&e.setDirty({change:"userData.constraints",source:"ObjectConstraintsPlugin.addConstraint"})),n}removeConstraint(e,t){if(!e.userData.constraints)return;const i=e.userData.constraints.indexOf(t);i!==-1&&(e.userData.constraints.splice(i,1),this._unregisterConstraint(t,e),e.setDirty&&e.setDirty({change:"userData.constraints",source:"ObjectConstraintsPlugin.addConstraint"}))}_refreshConstraint(e,t){const i=this._constraints.get(e);if(!i)return;const n=t!==void 0?t??void 0:this._viewer?.object3dManager.findObject(e.target),s=i.target;n!==s&&(this._removeTarget(s,e),this._addTarget(n,e)),i.target=n}_registerConstraint(e,t){if(this._constraints.has(e)){this._refreshConstraint(e);return}this._constraints.set(e,{obj:t}),this._constraintObjects.has(t)||this._constraintObjects.set(t,new Set),this._constraintObjects.get(t).add(e),this._refreshConstraint(e),e.refresh=()=>this._refreshConstraint(e),e.remove=()=>(this.removeConstraint(t,e),()=>{this.addConstraint(t,e)});const i=e.uiConfig,n=t.userData.constraints?.indexOf(e)??-1;if(i&&n>=0){const s=this._viewer?.getPlugin("AnimationObjectPlugin");if(s){const a=this._animatableComponents(e);a.length&&a.forEach(o=>s.setupUiConfigButton(t,o,"userData.constraints."+n.toString()+".props."))}}}_unregisterConstraint(e,t){if(!this._constraints.has(e))return;const i=this._constraints.get(e);if(i?.obj===t){this._removeTarget(i.target,e);const n=this._constraintObjects.get(t);if(n&&(n.delete(e),n.size===0&&this._constraintObjects.delete(t)),this._constraints.delete(e),e.refresh=void 0,e.uiConfig){const a=this._viewer?.getPlugin("AnimationObjectPlugin");a&&this._animatableComponents(e).forEach(o=>a.cleanupUiConfigButton(o))}}}_animatableComponents(e){return e?.uiConfig?.children?.flatMap(t=>it(t)).filter(t=>typeof t=="object"&&t.type==="number"&&t.property[1]==="offset"&&t.property[0]===e.props)||[]}_addTarget(e,t){if(!e)return;this._constraintTargets.has(e)||this._constraintTargets.set(e,new Set);const i=this._constraintTargets.get(e);i.has(t)||(i.add(t),t.setDirty())}_removeTarget(e,t){if(!e)return;const i=this._constraintTargets.get(e);i&&(i.has(t)&&(i.delete(t),t.setDirty()),i.size===0&&this._constraintTargets.delete(e))}_setupUiConfig(e){!(e.isObject3D||e.isMaterial)||!e.uiConfig||e.uiConfig?.children?.find(n=>typeof n=="object"&&n.tags?.includes(f.ObjectConstraintsPlugin.PluginType))||e.uiConfig?.children?.push({type:"folder",label:"Constraints",tags:["constraints",f.ObjectConstraintsPlugin.PluginType],children:[()=>e.userData.constraints?.map(n=>n.uiConfig),{type:"button",label:"Add Constraint",icon:"plus",tags:["context-menu","header-action"],onClick:()=>{const n=this.addConstraint(e);return()=>this.removeConstraint(e,n)}}]})}_cleanUpUiConfig(e){if(!e.uiConfig)return;const t=e.uiConfig?.children?.findIndex(i=>typeof i=="object"&&i.tags?.includes(f.ObjectConstraintsPlugin.PluginType));t!==void 0&&t>=0&&e.uiConfig.children?.splice(t,1)}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.scene.addEventListener("objectUpdate",this._objectUpdate)}onRemove(e){e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.scene.removeEventListener("objectUpdate",this._objectUpdate),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),super.onRemove(e)}},f.ObjectConstraintsPlugin.PluginType="ObjectConstraintsPlugin",f.ObjectConstraintsPlugin.ConstraintTypes=Ol,xo([ae(),z()],f.ObjectConstraintsPlugin.prototype,"enabled",2),f.ObjectConstraintsPlugin=xo([gt("Object Constraints")],f.ObjectConstraintsPlugin),f.ObjectConstraint=class{constructor(e){this.uuid=Ui(),this.enabled=!0,this.target="",this.influence=1,this.props={},this.needsUpdate=!1,this.setDirty=(t,i)=>{if(!(this.needsUpdate||t?.source===this.uuid)){if(typeof t!="object"&&(t=void 0),t){const n=Ol[this.type];if(t.key&&/.props\..+$/.test(t.key))this._propsUi.forEach(s=>s?.uiRefresh?.());else if(n?.setDirty&&!n.setDirty(t,i))return!1}return this.needsUpdate=!0,!0}},this.refresh2=()=>{this.refresh&&this.refresh(),this.setDirty()},this._propsUi=[],this.uiConfig={type:"folder",label:()=>this.type||"Constraint",tags:["constraint",f.ObjectConstraintsPlugin.PluginType],onChange:this.setDirty,children:[...vi(this),()=>{if(this._propsUi.length)return this._propsUi.forEach(i=>i.uiRefresh?.(!0)),this._propsUi;const t=vi(this.props).map(i=>it(i));return this._propsUi=t,t},{type:"button",tags:["context-menu"],label:"Remove Constraint",icon:"cross",property:[this,"remove"]}]},this.type=e??"copy_position",this.props=Ol[this.type]?.defaultProps||{},this.props||(this.props={})}update(e){const i=Ol[this.type]?.update(e.obj,e.target,this.props,this.influence);return i?.changed&&i.change&&e.obj.setDirty&&e.obj.setDirty({change:i.change,source:this.uuid}),this.needsUpdate=!(i.end??!0),i?.changed||!1}typeChanged(){const e=this.props;this.props=Ol[this.type]?.defaultProps||{};for(const t of Object.keys(this.props))if(e[t]!==void 0){const i=typeof this.props[t],n=typeof e[t];i===n&&(typeof i!="object"||i?.type&&i.type===n?.type)&&(this.props[t]=e[t])}this._propsUi=[],this.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}},xo([z(),ae()],f.ObjectConstraint.prototype,"enabled",2),xo([z(),de("typeChanged"),Oi(void 0,Object.keys(Ol).map(r=>({label:r})))],f.ObjectConstraint.prototype,"type",2),xo([z(),de("refresh2"),Fe()],f.ObjectConstraint.prototype,"target",2),xo([z(),Oe(void 0,[0,1],.01)],f.ObjectConstraint.prototype,"influence",2),xo([z()],f.ObjectConstraint.prototype,"props",2),f.ObjectConstraint=xo([Vc("ObjectConstraint")],f.ObjectConstraint);function h8(r){return{oneOf:r.map(e=>typeof e=="number"||typeof e=="boolean"?`${e}`:`"${e}"`),type:"Union"}}const Ab=class Ab{static AddClass(e){const t=e.ctor.prototype.serializableClassId;if(!t){console.error("Non Serializable class cannot be added to TypeSystem",e);return}t!==e.key&&console.warn(`TypeSystem: class serializableClassId "${t}" does not match registered className "${e.key}"`),this.Classes.set(e.key,e)}static GetClass(e){const t=typeof e=="string"?e:e.type;return this.Classes.get(t)}static GetClassType(e){for(const[t,i]of this.Classes)if(i.ctor===e)return t}static GetType(e,t=!0){if(e===void 0)return!1;if(e===null)return"null";if(typeof e=="function")return!1;if(typeof e=="number")return`${e}`;if(typeof e=="string")return`${JSON.stringify(e)}`;if(typeof e=="boolean")return`${e}`;if(Array.isArray(e)){const i=new Set;for(const s of e){const a=this.GetType(s);if(!a)return!1;i.add(a)}return{arrayOf:i.size===1?i.values().next().value:{oneOf:i,type:"Union"},type:"Array"}}if(typeof e=="object"){const i=e.constructor;if(i&&i!==Object){const s=this.GetClassType(i);if(s)return s;if(t){if(e.type&&Bt.SerializableClasses.has(e.type))return e.type;if(e.serializableClassId&&Bt.SerializableClasses.has(e.serializableClassId))return e.serializableClassId;const a=Bt.GetSerializer(e);return a&&typeof a.type=="string"&&!a.type.startsWith("_")?a.type:!1}}const n=new Map;for(const s in e){const a=e[s];if(typeof a=="function")continue;const o=this.GetType(a);if(!o)return!1;n.set(s,o)}return{recordOf:n,type:"Object"}}return!1}static NonLiteral(e){return typeof e!="string"?e:/^"(?:[^"\\]|\\.)*"$/.test(e)?"string":/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)?"number":e==="true"||e==="false"?"boolean":e==="Infinity"||e==="-Infinity"||e==="NaN"?"number":e}static TypeToString(e){return typeof e=="string"?e:"oneOf"in e?`(${Array.from(e.oneOf).map(t=>this.TypeToString(t)).join("|")})`:"arrayOf"in e?`Array<${this.TypeToString(e.arrayOf)}>`:"recordOf"in e?`{ ${Array.from(e.recordOf.entries()).map(([i,n])=>`${i}: ${this.TypeToString(n)}`).join("; ")} }`:e.type}static CanAssign(e,t){if(e===t)return!0;const i=this.GetClass(e),n=this.GetClass(t);if(i&&i===n)return!0;if(typeof t=="string"){if(typeof e=="string")return this.NonLiteral(e)===t;if("oneOf"in e){const s=e.oneOf;for(const a of s)if(!this.CanAssign(a,t))return!1;return!0}return"arrayOf"in e||"recordOf"in e,!1}if("oneOf"in t){const s=t.oneOf;for(const a of s)if(this.CanAssign(e,a))return!0;return!1}if("arrayOf"in t)return typeof e!="string"&&"arrayOf"in e?this.CanAssign(e.arrayOf,t.arrayOf):!1;if("recordOf"in t){if(typeof e!="string"&&"recordOf"in e){for(const[s,a]of t.recordOf){const o=e.recordOf.get(s);if(!o||!this.CanAssign(o,a))return!1}return!0}return!1}return!1}};Ab.Classes=new Map;let Hr=Ab;class aP{constructor(e){this.isItemRef=!0,this.id=e||""}toJSON(e){if(!this.id)return{};if(e&&(e.typed||(e.typed={}),!e.typed[this.id])){const t=Ra.Get(this);t&&(t.__rootPath?e.typed[this.id]={external:!0,rootPath:t.__rootPath,rootPathOptions:t.__rootPathOptions}:e.typed[this.id]=ke.Serialize(t,e))}return{id:this.id}}fromJSON(e,t){if(e&&typeof e.id=="string"&&(this.id=e.id,t?.typed)){const i=t.typed[this.id],n=t.__isLoadedResources,s=n&&i?i:ke.Deserialize(i,t);s?.external&&s.rootPath?console.warn("ReferenceManager - External resources is expected to be loaded already in ImportMeta phase:",s):(this._itemObject=s,n&&(t.typed[this.id]=s))}return this}}const tf=class tf{static Get(e){const t=this.Objects.get(e.id);return t?t.object:null}static Add(e,t,i){let n=this.Objects.get(e);n||(n={id:e,refs:new Map,object:t},this.Objects.set(e,n));let s=n.refs.get(i);s||(s=new Set,n.refs.set(i,s));const a=new aP(e);return s.add(a),a}static Remove(e,t,i){const n=this.Objects.get(e);if(n){const s=n.refs.get(t);s&&s.has(i)&&(s.delete(i),s.size===0&&(n.refs.delete(t),n.refs.size===0&&this.Objects.delete(e)))}}static Delete(e){if(e)for(const[t,i]of[...this.Objects])i.refs.delete(e),i.refs.size===0&&this.Objects.delete(t),i.object===e&&this.Objects.delete(t)}static RemoveOp(e,t){if(e!==void 0&&e.isItemRef){const i=e;tf.Remove(i.id,t,i)}}static GetOp(e,t=!0){if(e.isItemRef){const i=tf.Get(e);return i||(t&&console.error("Object3DComponent: Reference not found",e),null)}}static GetCached(e){if(e&&e.isItemRef&&e._itemObject){const t=e._itemObject;return e._itemObject=void 0,t}}};ke.MakeSerializable(aP,"ItemRef"),tf.Objects=new Map;let Ra=tf;function Lh(r){const e=new Set;let t=r;for(;t&&t!==Ba&&t!==Function.prototype;)t.ComponentType&&e.add(t.ComponentType),t=Object.getPrototypeOf(t);return e}function oP(r,e){if(!r.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");r.ctx=e;const t=f8(r.constructor),i=r.uiConfig??{type:"folder",label:()=>r._sType?`Missing (${r._sType})`:r.constructor.ComponentType,expanded:!1,children:vi(r)},n=i.children,s=[];t.forEach(a=>{const o=a.key;if(!qn(r,o)){console.error("Object3DComponent: state property not found on component",a,r);return}const l=a.default??r[o];if(l===void 0){console.error("Object3DComponent: state property default value must be set",a,r);return}const c=Hr.GetType(l);if(!c){console.error("Object3DComponent: unsupported type for state property",a,l);return}const h=a.type??Hr.NonLiteral(c);if(!Hr.CanAssign(c,h)){console.error("Object3DComponent: default value type is not compatible with state property type",a,l,c,h);return}delete r[o],Object.defineProperty(r,o,{get:()=>q_(r,o,l),set:d=>{lP(d,r,o,h,l)},enumerable:!0,configurable:!0}),cP(c,l,l,r,o);const u={config:a,propType:h,defaultValue:l,defaultValueType:c,propKey:o};if(s.push(u),n){const d=p8(r,u);d?.length&&n.push(...d)}}),Oh.InstanceProperties.set(r,s),n?.push({type:"button",label:"Reset to Default",uuid:"reset_to_default",tags:["context-menu"],value:()=>{const a={};return s.forEach(({propKey:o,defaultValue:l})=>{r[o]=l,a[o]=r[o]}),()=>{s.forEach(({propKey:o})=>{r[o]=a[o]})}}},{type:"button",label:"Remove Component",uuid:"remove_component",tags:["context-menu"],value:()=>e.ecp.removeComponent(r.object,r.uuid)}),r.uiConfig=i}function u8(r,e){if(!r.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");const t=Oh.InstanceProperties.get(r);if(t)for(const{propKey:i,defaultValue:n,propType:s}of t){const a=e?e[i]:void 0,o=r.stateRef[i];let l;const c=Ra.GetCached(o);c!==void 0?l=c:l=q_(r,i,n,o,!1),lP(l,r,i,s,n,a)}}function d8(r){if(!r.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");Ra.Delete(r),Oh.InstanceProperties.delete(r)}const qg=class qg{};qg.TypeProperties=new Map,qg.InstanceProperties=new Map;let Oh=qg;function f8(r){const e=Oh.TypeProperties.get(r);if(e)return e;const t=new Map;let i=r,n=0;for(;i&&i!==Function.prototype;){if(i.StateProperties)for(const s of i.StateProperties){const a=typeof s=="string"?s:s.key,o=t.get(a);if(o){const l=o[1];l===i?console.error("Object3DComponent: duplicate state property in class",{key:a,base:i}):console.warn("Object3DComponent: state property overridden in derived class",{key:a,base:i,constructor:l});continue}t.set(a,[typeof s=="string"?{key:s}:s,i,n]),n+=.001}if(i===Ba)break;i=Object.getPrototypeOf(i),n-=1}return Array.from(t.values()).sort((s,a)=>s[2]-a[2]).map(s=>s[0])}function q_(r,e,t,i,n=!0){if(i=i??r.stateRef[e],i===void 0)return t;const s=Ra.GetOp(i,n);return s!==void 0?s:i}function lP(r,e,t,i,n,s){if(r===void 0){console.error("Object3DComponent: state property cannot be set to undefined",t,r);return}const a=s!==void 0?q_(e,t,n,s):e[t];if(a===r)return;const o=Hr.GetType(r);if(!o){console.error("Object3DComponent: unsupported type for state property",t,r);return}if(!Hr.CanAssign(o,i)){console.error("Object3DComponent: assigned value type is not compatible with state property type",t,r,o,i);return}s===void 0&&(s=e.stateRef[t]),Ra.RemoveOp(s,e),cP(o,r,n,e,t),a!==void 0&&a!==r&&e.stateChangeHandlers[t]?.forEach(l=>l(r,a,t))}function cP(r,e,t,i,n){let s;const a=Hr.GetClass(r);if(a){const o=a.getId(e);if(o)s=Ra.Add(o,e,i);else{console.error("Object3DComponent: cannot get reference id for value of state property",n,e);return}}else e===t?s=void 0:s=e;s===void 0?delete i.stateRef[n]:i.stateRef[n]=s}function p8(r,e){const{config:t,propType:i,defaultValue:n,propKey:s}=e,a=typeof i=="string"?[i]:"oneOf"in i?Array.from(i.oneOf):["unknown"],o=a.includes("null"),l=a.map(d=>Hr.GetClass(d)).filter(d=>d!==void 0),c=[];if(l.length===a.length&&!o||l.length===a.length-1&&o){const d={type:"reference",label:t.label??s+"",property:[r,s],classTypes:l,allowNull:o,defaultValue:n};c.push(d)}const h=a.map(d=>typeof d=="string"?d.startsWith('"')&&d.endsWith('"')?JSON.parse(d):isNaN(Number(d))?d==="true"?!0:d==="false"?!1:typeof d=="number"||typeof d=="boolean"?d:void 0:Number(d):void 0).filter(d=>d!==void 0),u=()=>{const d=ti(r,s,t.label,void 0,!1);if(d)return typeof d=="object"&&(d.uuid=s,d.dispatchMode="immediate"),h.length>0&&h.length===a.length&&(d.type==="input"||d.type==="number"||d.type==="string")&&(d.type="dropdown",d.children=h.map(p=>({label:typeof p=="string"?p:typeof p=="number"?p.toString():typeof p=="boolean"?p?"true":"false":p+"",value:p}))),e.config.uiConfig&&Object.assign(d,e.config.uiConfig),d};return c.push(u),c}const Xg=class Xg{constructor(){this.isObject3DComponent=!0,this._object=null,this.uuid=Math.random().toString(32).slice(2,10),this.stateChangeHandlers={},this._state={}}get object(){if(!this._object)throw new Error("Cannot access object at this point.");return this._object}set object(e){console.error("Object3DComponent: object is read-only")}get stateRef(){return this._state}setState(e){const t=this._state;if(e!==t){e&&typeof e=="object"?this._state=e:this._state={};for(const i in t)i in this._state||(this._state[i]=t[i]);return u8(this,t),this}}start(){}stop(){}update(e){}preFrame(e){}init(e,t){if(!e)throw new Error("Object3DComponent: no object");this._object=e,this.setState(t)}destroy(){this._object=null,this.stateChangeHandlers={};const e=this._state;return this._state={},e}onStateChange(e,t){this.stateChangeHandlers[e]||(this.stateChangeHandlers[e]=[]),this.stateChangeHandlers[e].push(t)}getComponent(e,t=!1){const i=this._object;return i?t?Uh.GetComponent(i,e):Uh.GetComponentInParent(i,e)||this.ctx.ecp.getComponentOfType(e):t?null:this.ctx.ecp.getComponentOfType(e)}};Xg.StateProperties=[],Xg.ComponentType="Object3DComponent";let Ba=Xg;var m8=Object.defineProperty,zg=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&m8(e,t,n),n};const Yg=class Yg extends Ba{constructor(){super(...arguments),this.running=!0,this.mass=1,this.damping=.98,this.velocity=new x,this.acceleration=new x,this.MoveLeft=()=>{this.applyImpulse({x:-5})},this.MoveRight=()=>{this.applyImpulse({x:5})},this.PushForward=async()=>{for(let e=0;e<200;e++)this.addForce({z:10}),await jn(32)},this.PushBackward=async()=>{for(let e=0;e<200;e++)this.addForce({z:-10}),await jn(32)}}update({deltaTime:e}){if(!this.object||!this.running)return;const t=(e??16)/1e3;return this.velocity.x+=this.acceleration.x*t,this.velocity.y+=this.acceleration.y*t,this.velocity.z+=this.acceleration.z*t,this.velocity.multiplyScalar(this.damping),this.acceleration.set(0,0,0),Math.abs(this.velocity.x)+Math.abs(this.velocity.y)+Math.abs(this.velocity.z)<=1e-6?!1:(this.object.position.x+=this.velocity.x*t,this.object.position.y+=this.velocity.y*t,this.object.position.z+=this.velocity.z*t,!0)}addForce(e){e.x!==void 0&&(this.acceleration.x+=e.x/this.mass),e.y!==void 0&&(this.acceleration.y+=e.y/this.mass),e.z!==void 0&&(this.acceleration.z+=e.z/this.mass)}applyImpulse(e){e.x!==void 0&&(this.velocity.x+=e.x/this.mass),e.y!==void 0&&(this.velocity.y+=e.y/this.mass),e.z!==void 0&&(this.velocity.z+=e.z/this.mass)}setVelocity(e){this.velocity.copy(e)}stop(){this.reset()}start(){this.reset()}reset(){this.velocity.set(0,0,0),this.acceleration.set(0,0,0)}};Yg.StateProperties=["running","mass","damping"],Yg.ComponentType="SampleBodyComponent";let Ul=Yg;zg([lt()],Ul.prototype,"MoveLeft"),zg([lt()],Ul.prototype,"MoveRight"),zg([lt()],Ul.prototype,"PushForward"),zg([lt()],Ul.prototype,"PushBackward");const Gt=class Gt extends pt{constructor(e=!0){super(),this.enabled=!0,this._components=new Map,this._typeToComponents=new Map,this.componentTypes=new Map,this._onRemove=[],this._preFrame=t=>{if(this.isDisabled()||!this._viewer?.renderEnabled||t.deltaTime<=0)return;const i=[t];let n=!1,s=this.componentsDispatch("preFrame",...i);!n&&s.find(a=>!!a[1])&&(n=!0),this._running&&t.timeline.delta>0&&(s=this.componentsDispatch("update",...i),!n&&s.find(a=>!!a[1])&&(n=!0)),n&&this._viewer?.setDirty(this)},this._objectAdd=t=>{const i=t.object;if(!i||i.isWidget)return;if(i.getComponent||(i.getComponent=(s,a=!1)=>a?Gt.GetComponent(i,s):Gt.GetComponentInParent(i,s)||this.getComponentOfType(s)),!i._compUiInit&&i.uiConfig?.children&&Gt.AddObjectUiConfig){i._compUiInit=!0;const s={type:"dropdown",label:"Add Component",value:"",children:[{label:"Select component type",value:""},()=>[...this.componentTypes.values()].map(a=>({label:a.ComponentType,value:a.ComponentType}))]};i.uiConfig.children.push({type:"folder",label:"Components",tags:[Gt.PluginType],children:[s,{type:"button",label:"Add Component",onClick:()=>{if(s.value)return this.addComponent(i,s.value)}},()=>{const a=Gt.GetObjectData(i);return a?Object.keys(a).map(l=>this._components.get(i.uuid+l)?.uiConfig).filter(l=>!!l):[]}]})}const n=Gt.GetObjectData(i);n&&Object.entries(n).forEach(([s,a])=>{if(t.componentType&&a.type!==t.componentType)return;const o=this.registerComponent(i,a,s);o&&(n[s].state=o.stateRef)})},this._objectRemove=t=>{const i=t.object;if(!i)return;const n=Gt.GetObjectData(i);i.getComponent&&delete i.getComponent,i._compUiInit&&i.uiConfig?.children&&(i._compUiInit=!1,i.uiConfig.children=i.uiConfig.children.filter(s=>{if(typeof s=="object"&&s.tags&&Array.isArray(s.tags)&&s.tags.includes(Gt.PluginType))return!1})),n&&Object.entries(n).forEach(([s,a])=>{if(t.componentType&&a.type!==t.componentType)return;const o=this._components.get(i.uuid+s);if(o){if(o.object!==i){console.warn(`EntityComponentPlugin: component with id ${s} exists on a different object`);return}const l=this.unregisterComponent(o);l&&(a.state=l)}})},this._objectUpdate=t=>{if(t.change==="deserialize"){if(!t.object)return;this._objectAdd(t)}},this.componentTypes.set(Ba.ComponentType,Ba),this._running=e}get running(){return this._running}start(){if(!this._running){this._running=!0;for(const e of this._components.values())try{e.start()}catch(t){console.error("EntityComponentPlugin: Error starting component",e),console.error(t)}this._viewer&&this._components.size&&this._viewer.setDirty(this)}}stop(){if(this._running){this._running=!1;for(const e of this._components.values())try{e.stop()}catch(t){console.error("EntityComponentPlugin: Error stopping component",e),console.error(t)}this._viewer&&this._components.size&&this._viewer.setDirty(this)}}componentsDispatch(e,...t){return Gt.ComponentsDispatch([...this._components.values()],e,t)}static ObjectDispatch(e,t,...i){const n=Gt.ObjectToComponents.get(e);return n?Gt.ComponentsDispatch(n,t,i):[]}static ComponentsDispatch(e,t,i){const n=[];for(const s of e){const a=s[t];if(typeof a=="function")try{n.push([s,a.apply(s,i)])}catch(o){console.error(`EntityComponentPlugin: Error in component ${s.constructor.ComponentType} handling ${t}`,s,o)}}return n}addComponentType(e){if(!e||typeof e!="function")throw new Error("EntityComponentPlugin: invalid component type");if(!e.ComponentType||typeof e.ComponentType!="string")throw new Error('EntityComponentPlugin: component type must have a valid string "ComponentType" property');return this.componentTypes.has(e.ComponentType)?(console.warn(`EntityComponentPlugin: component type "${e.ComponentType}" already registered`),!1):(this.componentTypes.set(e.ComponentType,e),this.dispatchEvent({type:"addComponentType",cls:e}),this._viewer?.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t,componentType:e.ComponentType})),!0)}removeComponentType(e){if(!e||typeof e!="function")throw new Error("EntityComponentPlugin: invalid component type");if(!e.ComponentType||typeof e.ComponentType!="string")throw new Error('EntityComponentPlugin: component type must have a valid string "ComponentType" property');return this.componentTypes.has(e.ComponentType)?(this.dispatchEvent({type:"removeComponentType",cls:e}),this._viewer?.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t,componentType:e.ComponentType})),this.componentTypes.delete(e.ComponentType),!0):(console.warn(`EntityComponentPlugin: component type "${e.ComponentType}" not registered`),!1)}hasComponentType(e){const t=typeof e=="string"?e:e.ComponentType;return this.componentTypes.has(t)}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(i=>this._objectAdd({object:i})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.scene.addEventListener("objectUpdate",this._objectUpdate);const t=e.on("preFrame",{order:1,callback:this._preFrame});t&&this._onRemove.push(t)}onRemove(e){e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),e.scene.removeEventListener("objectUpdate",this._objectUpdate),this._onRemove.forEach(t=>t()),super.onRemove(e)}static GetObjectData(e){let t=e.userData[Gt.UserDataKey];return t&&typeof t!="object"&&(console.warn(`EntityComponentPlugin: userData.${Gt.UserDataKey} is not an object`,e),t={},e.userData[Gt.UserDataKey]=t),t||null}addComponent(e,t,i){if(!this._viewer)throw new Error("EntityComponentPlugin: no viewer");const n=t?typeof t=="string"?{type:t,state:{}}:t.ComponentType?{type:t.ComponentType,state:{}}:t&&typeof t.type=="string"&&t.state?t:{type:"Object3DComponent",state:{}}:{type:"Object3DComponent",state:{}};t.ComponentType&&(this.hasComponentType(t)||this.addComponentType(t));const s=this.registerComponent(e,n,i);if(!s)throw new Error("EntityComponentPlugin: cannot create component of type "+n.type);let a=Gt.GetObjectData(e);a||(a={},e.userData[Gt.UserDataKey]=a),a[s.uuid]?(a[s.uuid].type=s.constructor.ComponentType,a[s.uuid].state=s.stateRef):a[s.uuid]={state:s.stateRef,type:s.constructor.ComponentType},e.setDirty&&e.setDirty({change:`userData.${Gt.UserDataKey}`,source:"EntityComponentPlugin.addComponent",refreshUi:!0});const o={undo:()=>{const l=this.removeComponent(e,o.component.uuid);l&&(o.redo=l.undo)},redo:()=>{this.addComponent(e,t)},component:s};return o}removeComponent(e,t){if(!this._viewer)return;const i=this._components.get(e.uuid+t);if(!i)return;const n=i.constructor.ComponentType,s=this.unregisterComponent(i),a=Gt.GetObjectData(e);a&&(delete a[t],Object.keys(a).length===0&&delete e.userData[Gt.UserDataKey],e.setDirty&&e.setDirty({change:`userData.${Gt.UserDataKey}`,source:"EntityComponentPlugin.removeComponent",refreshUi:!0}));const o={state:s,undo:()=>{o.state&&this.addComponent(e,{type:n,state:o.state},t)},redo:()=>{this.removeComponent(e,t)}};return o}static GetComponentData(e,t){if(!e)return null;const i=Gt.GetObjectData(e);if(!i)return null;const n=typeof t=="string"?[t]:[...Lh(t)];for(const[a,o]of Object.entries(i))for(const l of n)if(o.type===l)return{id:a,...o};const s=Gt.GetComponent(e,t);return s?{id:s.uuid,type:s.constructor.ComponentType,state:s.stateRef}:null}static GetComponents(e,t){if(!e)return[];const i=Gt.ObjectToComponents.get(e)||[];if(!t)return i;const n=typeof t=="string"?[t]:[...Lh(t)];return i.filter(s=>{const a=Lh(s.constructor);return n.some(o=>a.has(o))})}static GetComponent(e,t){if(!e)return null;const i=Gt.ObjectToComponents.get(e)||[],n=typeof t=="string"?[t]:[...Lh(t)];for(const s of i){const a=Lh(s.constructor);for(const o of n)if(a.has(o))return s}return null}static GetComponentInParent(e,t){if(!e)return null;let i=e,n=null;for(;!n&&i;)n=Gt.GetComponent(i,t),i=i.parent;return n}static GetComponentsInParent(e,t){if(!e)return[];let i=e;const n=[];for(;i;)n.push(...Gt.GetComponents(i,t)),i=i.parent;return n}getComponentsOfType(e){const t=typeof e=="string"?e:e.ComponentType,i=this._typeToComponents.get(t);return i?[...i]:[]}getComponentOfType(e){const t=typeof e=="string"?e:e.ComponentType,i=this._typeToComponents.get(t);return!i||i.size===0?null:i.values().next().value}registerComponent(e,t,i){if(!this._viewer)throw new Error("EntityComponentPlugin: no viewer");if(!e)throw new Error("EntityComponentPlugin: no object");if((!t||typeof t!="object")&&(console.warn("EntityComponentPlugin: invalid component state",t,e),t={type:"Object3DComponent",state:{}}),i){const l=this._components.get(e.uuid+i);if(l)return l.object!==e&&(console.error(`EntityComponentPlugin: component with id ${i} already exists on a different object`),l.object=e),l.constructor.ComponentType!==t.type?(console.warn(`EntityComponentPlugin: component with id ${i} type mismatch (${l.constructor.ComponentType} != ${t.type}), removing previous component and creating new one`),this.unregisterComponent(l)):l.setState(t.state),l}const n=this.componentTypes.get(t.type),s={viewer:this._viewer,ecp:this,plugin:l=>{const c=s.viewer?.getPlugin(l);if(!c)throw new Error(`EntityComponentPlugin: cannot find plugin ${typeof l=="string"?l:l.name}`);return c}};let a;try{a=n?new n:new Ba,n||(console.error("EntityComponentPlugin: unknown component type "+t.type,e),a._sType=t.type),i&&(a.uuid=i),oP(a,s)}catch(l){return console.error("EntityComponentPlugin: Error creating component of type "+t.type),console.error(l),null}this._components.set(e.uuid+a.uuid,a),Gt.ObjectToComponents.set(e,[...Gt.ObjectToComponents.get(e)||[],a]);const o=this._typeToComponents.get(a.constructor.ComponentType)||new Set;o.add(a),this._typeToComponents.set(a.constructor.ComponentType,o);try{a.init(e,t.state)}catch(l){console.error("EntityComponentPlugin: Error initializing component",a),console.error(l)}this.dispatchEvent({type:"registerComponent",component:a,object:e});try{this.running&&a.start()}catch(l){console.error("EntityComponentPlugin: Error starting component",a),console.error(l)}return a}unregisterComponent(e){if(!e)return;const t=e.object;let i=null;if(!t)console.warn("EntityComponentPlugin: component already destroyed",e);else{try{this.running&&e.stop()}catch(o){console.error("EntityComponentPlugin: Error stopping component",e),console.error(o)}try{i=e.destroy()}catch(o){console.error("EntityComponentPlugin: Error destroying component",e),console.error(o)}}this._components.delete(t.uuid+e.uuid);const n=this._typeToComponents.get(e.constructor.ComponentType);n&&(n.delete(e),n.size===0&&this._typeToComponents.delete(e.constructor.ComponentType)),d8(e);const s=Gt.ObjectToComponents.get(t)||[],a=s.indexOf(e);return a!==-1&&(s.splice(a,1),s.length===0&&Gt.ObjectToComponents.delete(t)),t&&this.dispatchEvent({type:"unregisterComponent",component:e,object:t}),i}};Gt.PluginType="EntityComponentPlugin",Gt.ObjectToComponents=new Map,Gt.UserDataKey=Gt.PluginType,Gt.AddObjectUiConfig=!0;let Uh=Gt;const g8=Uh;function A8(){window.dispatchEvent(new Event("threepipe-test-finished")),document.body.classList.add("_testFinish")}function y8(){window.dispatchEvent(new Event("threepipe-test-started")),document.body.classList.add("_testStarted")}function v8(r){return Ge.autoCenter.call(r)}function _8(r,e,t,i){return Ge.autoScale.call(r,e,t,i)}f.AAssetManagerProcessStatePlugin=uI,f.ACESFilmicToneMapping=EH,f.ACameraControlsPlugin=xg,f.ACameraHelperWidget=bI,f.AGeometryGenerator=gr,f.AHelperWidget=Ch,f.ALightHelperWidget=Ig,f.AScreenPassExtensionPlugin=Gd,f.AViewerPlugin=Zc,f.AViewerPluginAsync=zN,f.AViewerPluginSync=pt,f.AddEquation=jV,f.AddOperation=bH,f.AdditiveAnimationBlendMode=c4,f.AdditiveBlending=zV,f.AgXToneMapping=TH,f.AlphaFormat=cQ,f.AlwaysCompare=$4,f.AlwaysDepth=dH,f.AlwaysStencilFunc=V4,f.AmbientLight=Rp,f.AmbientLight2=vl,f.AnimationAction=xx,f.AnimationClip=eo,f.AnimationLoader=bO,f.AnimationMixer=Sx,f.AnimationObjectGroup=HO,f.AnimationObjectPlugin=sW,f.AnimationUtils=AO,f.ArcCurve=hp,f.ArrayCamera=gC,f.ArrowHelper=oU,f.AssetExporter=E1,f.AssetExporterPlugin=Rg,f.AssetImporter=Bs,f.AssetManager=gg,f.AsyncCompress=zT,f.AsyncDecompress=$G,f.AsyncDeflate=kT,f.AsyncGunzip=HT,f.AsyncGzip=zT,f.AsyncInflate=V0,f.AsyncUnzipInflate=az,f.AsyncUnzlib=jT,f.AsyncZipDeflate=iz,f.AsyncZlib=XG,f.AttachedBindMode=PH,f.Audio=bx,f.AudioAnalyser=BO,f.AudioContext=Oy,f.AudioListener=PO,f.AudioLoader=MO,f.AxesHelper=lU,f.BackSide=FV,f.BaseImporterPlugin=Pl,f.BasicDepthPacking=f4,f.BasicShadowMap=RV,f.BatchedMesh=RC,f.Bone=Pc,f.BoneHelper=yj,f.BooleanKeyframeTrack=Zo,f.Box2=ky,f.Box3=en,f.Box3B=In,f.Box3Helper=rU,f.BoxGeometry=mi,f.BoxGeometryGenerator=YI,f.BoxHelper=sU,f.BoxSelectionWidget=wI,f.BufferAttribute=Xe,f.BufferGeometry=$e,f.BufferGeometry2=_d,f.BufferGeometryLoader=Ly,f.ByteType=JH,f.CSMFrustum=$d,f.Cache=di,f.Camera=Ac,f.CameraHelper=nU,f.CameraHelper2=CI,f.CameraViewPlugin=n_,f.CanvasSnapshot=md,f.CanvasSnipperPlugin=B_,f.CanvasTexture=Wo,f.CapsuleGeometry=pp,f.CascadedShadowsPlugin=TW,f.CatmullRomCurve3=Oc,f.CineonToneMapping=SH,f.CircleGeometry=mp,f.CircleGeometryGenerator=XI,f.ClampToEdgeWrapping=kH,f.Clock=Lu,f.Color=se,f.ColorKeyframeTrack=My,f.ColorManagement=Xt,f.Compress=sg,f.CompressedArrayTexture=GC,f.CompressedCubeTexture=zC,f.CompressedTexture=ua,f.CompressedTextureLoader=lx,f.ConeGeometry=gp,f.ConstantAlphaFactor=cH,f.ConstantColorFactor=oH,f.ConvexHull=B5,f.CopyShader=bl,f.CubeCamera=Gw,f.CubeReflectionMapping=BH,f.CubeRefractionMapping=LH,f.CubeTexture=_c,f.CubeTextureLoader=wO,f.CubeUVReflectionMapping=FH,f.CubicBezierCurve=bu,f.CubicBezierCurve3=dp,f.CubicInterpolant=rx,f.CullFaceBack=IV,f.CullFaceFront=PV,f.CullFaceFrontBack=DV,f.CullFaceNone=TV,f.Curve=Ps,f.CurvePath=Su,f.CurvePath3=Cm,f.CustomBlending=QV,f.CustomContextMenu=Wu,f.CustomToneMapping=MH,f.CylinderGeometry=sn,f.CylinderGeometryGenerator=JI,f.Cylindrical=XO,f.DRACOLoader=d1,f.DRACOLoader2=fg,f.Damper=hU,f.Data3DTexture=wf,f.DataArrayTexture=bf,f.DataTexture=As,f.DataTextureLoader=Iy,f.DataUtils=Hn,f.DecodeUTF8=ZG,f.Decompress=j0,f.DecrementStencilOp=D4,f.DecrementWrapStencilOp=B4,f.DefaultLoadingManager=Ty,f.Deflate=Js,f.DepthFormat=pQ,f.DepthNormalMaterial=qN,f.DepthStencilFormat=mQ,f.DepthTexture=jf,f.DetachedBindMode=DH,f.DeviceOrientationControlsPlugin=x_,f.DirectionalLight=il,f.DirectionalLight2=Qm,f.DirectionalLightHelper=iU,f.DirectionalLightHelper2=xI,f.DiscreteInterpolant=ax,f.DisplayP3ColorSpace=_4,f.DodecahedronGeometry=Ap,f.DoubleSide=NV,f.Dropzone=Zp,f.DstAlphaFactor=iH,f.DstColorFactor=sH,f.DuplicateTracker=Dg,f.DynamicCopyUsage=s5,f.DynamicDrawUsage=J4,f.DynamicImportPlugin=W_,f.DynamicReadUsage=t5,f.ECS=g8,f.EXRExporter=v1,f.EXRExporter2=i_,f.EXRLoader=Z0,f.EasingFunctions=Kc,f.EdgesGeometry=HC,f.EffectComposer=jM,f.EffectComposer2=WM,f.EllipseCurve=qo,f.EllipseCurve3D=yl,f.EncodeUTF8=ez,f.EntityComponentPlugin=Uh,f.EqualCompare=j4,f.EqualDepth=mH,f.EqualStencilFunc=F4,f.EquirectangularReflectionMapping=OH,f.EquirectangularRefractionMapping=UH,f.Euler=Tt,f.EventDispatcher=wi,f.ExtendedCopyPass=y0,f.ExtendedRenderPass=A0,f.ExtendedShaderMaterial=RM,f.ExtendedShaderPass=nh,f.ExtrudeGeometry=xp,f.FBXLoader=i1,f.FBXLoader2=c1,f.Face=Zs,f.FileLoader=Zt,f.FileTransferPlugin=L_,f.FlateErrorCode=WG,f.Float16BufferAttribute=SD,f.Float32BufferAttribute=Me,f.FloatType=nQ,f.FnCaller=zu,f.Fog=$f,f.FogExp2=Yf,f.FragmentClippingMode=Yd,f.FrameFadeBlendPass=AI,f.FramebufferTexture=zL,f.FrontSide=UV,f.Frustum=hu,f.FullScreenQuad=GM,f.GBufferMaterial=km,f.GLBufferAttribute=qO,f.GLSL1=a5,f.GLSL3=o5,f.GLStatsJS=gS,f.GLTFAnimationPlugin=tW,f.GLTFBinaryExtension=w0,f.GLTFExporter=xd,f.GLTFExporter2=mg,f.GLTFKHRMaterialVariantsPlugin=n8,f.GLTFLightExtrasExtension=Ed,f.GLTFLoader=xt,f.GLTFLoader2=Ml,f.GLTFMaterialExtrasExtension=Md,f.GLTFMaterialsAlphaMapExtension=wl,f.GLTFMaterialsBumpMapExtension=rh,f.GLTFMaterialsDisplacementMapExtension=Cl,f.GLTFMaterialsLightMapExtension=xl,f.GLTFMeshOptDecodePlugin=R_,f.GLTFObject3DExtrasExtension=Td,f.GLTFParser=hT,f.GLTFViewerConfigExtension=fo,f.GLTFWriter2=nT,f.GPUComputationRenderer=I5,f.GenericBlendTexturePass=zM,f.GeometryGeneratorPlugin=Ph,f.GreaterCompare=q4,f.GreaterDepth=AH,f.GreaterEqualCompare=Y4,f.GreaterEqualDepth=gH,f.GreaterEqualStencilFunc=z4,f.GreaterStencilFunc=k4,f.GridHelper=eU,f.Group=Ri,f.Group2=Al,f.Gunzip=ag,f.Gzip=sg,f.HVBlurHelper=KS,f.HalfEdge=Cg,f.HalfFloatType=sQ,f.HemisphereLight=Dp,f.HemisphereLight2=Ca,f.HemisphereLightHelper=ZO,f.HorizontalBlurShader=YS,f.IcosahedronGeometry=Sp,f.ImageBitmapLoader=gx,f.ImageLoader=Gc,f.ImageUtils=PA,f.Importer=qi,f.IncrementStencilOp=P4,f.IncrementWrapStencilOp=R4,f.Inflate=_s,f.InstancedBufferAttribute=ha,f.InstancedBufferGeometry=By,f.InstancedInterleavedBuffer=Ou,f.InstancedMesh=Bc,f.InstancedMesh2=ak,f.Int16BufferAttribute=CD,f.Int32BufferAttribute=xD,f.Int8BufferAttribute=_D,f.IntType=tQ,f.InterleavedBuffer=Sc,f.InterleavedBufferAttribute=On,f.Interpolant=kc,f.InterpolateDiscrete=i4,f.InterpolateLinear=n4,f.InterpolateSmooth=s4,f.InvertStencilOp=L4,f.JSONMaterialLoader=oh,f.JSUndoManager=Hy,f.KHR_TEXTURE_BASISU=D_,f.KTX2LoadPlugin=Xd,f.KTX2Loader=dr,f.KTX2Loader2=NI,f.KTXLoadPlugin=P_,f.KTXLoader=tI,f.KeepStencilOp=T4,f.KeyframeTrack=lr,f.LOD=bC,f.LatheGeometry=Eu,f.Layers=If,f.LegacyPhongMaterial=Gm,f.LessCompare=Q4,f.LessDepth=fH,f.LessEqualCompare=W4,f.LessEqualDepth=pH,f.LessEqualStencilFunc=N4,f.LessStencilFunc=U4,f.Light=io,f.LightProbe=fx,f.Line=fn,f.Line2=Vm,f.Line3=Gy,f.LineBasicMaterial=Ei,f.LineBasicMaterial2=nk,f.LineCurve=Xo,f.LineCurve3=Yo,f.LineDashedMaterial=ix,f.LineGeometry=vd,f.LineGeometry2=d0,f.LineGeometryGenerator=Ng,f.LineHelper=SI,f.LineLoop=dy,f.LineMaterial=$c,f.LineMaterial2=ji,f.LineSegments=Is,f.LineSegments2=_a,f.LineSegmentsGeometry=Hs,f.LineSegmentsGeometry2=UM,f.LinearDisplayP3ColorSpace=b4,f.LinearEncoding=h5,f.LinearFilter=WH,f.LinearInterpolant=Ey,f.LinearMipMapLinearFilter=$H,f.LinearMipMapNearestFilter=XH,f.LinearMipmapLinearFilter=YH,f.LinearMipmapNearestFilter=qH,f.LinearSRGBColorSpace=v4,f.LinearToSRGB=qx,f.LinearToneMapping=CH,f.LinearTransfer=C4,f.Loader=li,f.LoaderUtils=Rs,f.LoadingManager=Pp,f.LoopOnce=ZQ,f.LoopPingPong=t4,f.LoopRepeat=e4,f.LuminanceAlphaFormat=fQ,f.LuminanceFormat=dQ,f.MOUSE=EV,f.MTLLoader2=T0,f.Material=tn,f.MaterialConfiguratorBasePlugin=PW,f.MaterialExtender=gl,f.MaterialLoader=Bu,f.MaterialManager=M1,f.MaterialPreviewGenerator=JS,f.MathUtils=Ut,f.Matrix2=Fp,f.Matrix3=mt,f.Matrix4=pe,f.MaxEquation=YV,f.Mesh=ye,f.Mesh2=zm,f.MeshBasicMaterial=ss,f.MeshBasicMaterial2=HN,f.MeshDepthMaterial=xc,f.MeshDepthMaterialOverride=pI,f.MeshDistanceMaterial=sy,f.MeshLambertMaterial=Cy,f.MeshLine=u0,f.MeshLineMaterial=rk,f.MeshLineSegments=LM,f.MeshMatcapMaterial=tx,f.MeshNormalMaterial=wy,f.MeshNormalMaterialOverride=gI,f.MeshPhongMaterial=Ko,f.MeshPhysicalMaterial=Nc,f.MeshStandardMaterial=Ka,f.MeshStandardMaterial2=ik,f.MeshSurfaceSampler=P5,f.MeshToonMaterial=ex,f.MetaImporter=Em,f.MinEquation=XV,f.MirroredRepeatWrapping=GH,f.MixOperation=_H,f.MultiplyBlending=HV,f.MultiplyOperation=vH,f.NearestFilter=zH,f.NearestMipMapLinearFilter=jH,f.NearestMipMapNearestFilter=HH,f.NearestMipmapLinearFilter=QH,f.NearestMipmapNearestFilter=VH,f.NeutralToneMapping=IH,f.NeverCompare=H4,f.NeverDepth=uH,f.NeverStencilFunc=O4,f.NoBlending=kV,f.NoColorSpace=A4,f.NoToneMapping=wH,f.NormalAnimationBlendMode=l4,f.NormalBlending=GV,f.NotEqualCompare=X4,f.NotEqualDepth=yH,f.NotEqualStencilFunc=G4,f.NumberKeyframeTrack=Ja,f.OBJLoader2=yT,f.Object3D=ft,f.Object3D2=BM,f.Object3DComponent=Ba,f.Object3DManager=Ag,f.Object3DWidgetsPlugin=zW,f.ObjectClipboard=DI,f.ObjectLoader=Lp,f.ObjectPicker=XS,f.ObjectShaderMaterial=h0,f.ObjectSpaceNormalMap=g4,f.OctahedronGeometry=da,f.OneFactor=KV,f.OneMinusConstantAlphaFactor=hH,f.OneMinusConstantColorFactor=lH,f.OneMinusDstAlphaFactor=nH,f.OneMinusDstColorFactor=rH,f.OneMinusSrcAlphaFactor=tH,f.OneMinusSrcColorFactor=ZV,f.OrbitControls=ov,f.OrbitControls2=LF,f.OrthographicCamera=Mr,f.OrthographicCamera0=DM,f.OrthographicCamera2=yd,f.P3Primaries=E4,f.PCFShadowMap=BV,f.PCFSoftShadowMap=LV,f.PLYLoadPlugin=T_,f.PLYLoader=nI,f.PMREMGenerator=ey,f.Pass=wd,f.Path=Uc,f.PerspectiveCamera=Vi,f.PerspectiveCamera0=PM,f.PerspectiveCamera2=th,f.PhysicalMaterial=ai,f.PickingPlugin=ws,f.PipelinePassPlugin=Tl,f.PivotControls=Qc,f.Plane=Ts,f.PlaneGeometry=Er,f.PlaneGeometryGenerator=KI,f.PlaneHelper=aU,f.PointLight=tl,f.PointLight2=jm,f.PointLightHelper=KO,f.PointLightHelper2=MI,f.PointerDragHelper=Fx,f.PointerLockControlsPlugin=S_,f.Points=jo,f.PointsMaterial=Tr,f.PolarGridHelper=tU,f.PolyhedronGeometry=Ya,f.PopmotionPlugin=Vr,f.PositionalAudio=RO,f.ProgressiveBlendPass=fI,f.PropertyBinding=Ct,f.PropertyMixer=Cx,f.QuadraticBezierCurve=wu,f.QuadraticBezierCurve3=Cu,f.Quaternion=Qe,f.QuaternionKeyframeTrack=Ir,f.QuaternionLinearInterpolant=ox,f.RED_GREEN_RGTC2_Format=KQ,f.RED_RGTC1_Format=YQ,f.REVISION=SV,f.RGBADepthPacking=p4,f.RGBAFormat=uQ,f.RGBAIntegerFormat=_Q,f.RGBA_ASTC_10x10_Format=HQ,f.RGBA_ASTC_10x5_Format=GQ,f.RGBA_ASTC_10x6_Format=zQ,f.RGBA_ASTC_10x8_Format=VQ,f.RGBA_ASTC_12x10_Format=QQ,f.RGBA_ASTC_12x12_Format=jQ,f.RGBA_ASTC_4x4_Format=RQ,f.RGBA_ASTC_5x4_Format=BQ,f.RGBA_ASTC_5x5_Format=LQ,f.RGBA_ASTC_6x5_Format=OQ,f.RGBA_ASTC_6x6_Format=UQ,f.RGBA_ASTC_8x5_Format=FQ,f.RGBA_ASTC_8x6_Format=NQ,f.RGBA_ASTC_8x8_Format=kQ,f.RGBA_BPTC_Format=WQ,f.RGBA_ETC2_EAC_Format=DQ,f.RGBA_PVRTC_2BPPV1_Format=TQ,f.RGBA_PVRTC_4BPPV1_Format=MQ,f.RGBA_S3TC_DXT1_Format=wQ,f.RGBA_S3TC_DXT3_Format=CQ,f.RGBA_S3TC_DXT5_Format=xQ,f.RGBELoader=T1,f.RGBEPNGLoader=sT,f.RGBFormat=hQ,f.RGBM16ColorSpace=w4,f.RGB_BPTC_SIGNED_Format=qQ,f.RGB_BPTC_UNSIGNED_Format=XQ,f.RGB_ETC1_Format=IQ,f.RGB_ETC2_Format=PQ,f.RGB_PVRTC_2BPPV1_Format=EQ,f.RGB_PVRTC_4BPPV1_Format=SQ,f.RGB_S3TC_DXT1_Format=bQ,f.RGFormat=yQ,f.RGIntegerFormat=vQ,f.RawShaderMaterial=ZC,f.Ray=Ha,f.Raycaster=Uu,f.Rec709Primaries=S4,f.RectAreaLight=Bp,f.RectAreaLight2=Nr,f.RedFormat=gQ,f.RedIntegerFormat=AQ,f.ReferenceManager=Ra,f.ReinhardToneMapping=xH,f.RenderPass=p0,f.RenderTarget=_w,f.RenderTargetManager=XM,f.RepeatWrapping=NH,f.ReplaceStencilOp=I4,f.ReverseSubtractEquation=qV,f.Rhino3dmLoader=f1,f.Rhino3dmLoader2=ur,f.RingGeometry=Ep,f.SIGNED_RED_GREEN_RGTC2_Format=JQ,f.SIGNED_RED_RGTC1_Format=$Q,f.SRGBColorSpace=y4,f.SRGBToLinear=_U,f.SRGBTransfer=x4,f.STLLoadPlugin=I_,f.STLLoader=sI,f.SVGTextureLoader=pg,f.SampleBodyComponent=Ul,f.Scene=qa,f.SceneUiConfigPlugin=Mg,f.SelectionWidget=_I,f.Serialization=Bt,f.ShaderChunk=ot,f.ShaderLib=Di,f.ShaderMaterial=nn,f.ShaderMaterial2=gd,f.ShaderPass=m0,f.ShadowMaterial=JC,f.Shape=ar,f.ShapeGeometry=Pu,f.ShapeGeometryGenerator=tP,f.ShapePath=cU,f.ShapeUtils=or,f.ShortType=ZH,f.SimpleEventDispatcher=Qp,f.SimpleJSONExporter=g1,f.SimpleJSONLoader=Pd,f.SimpleTextExporter=A1,f.SimplifyModifierPlugin=Ll,f.Skeleton=Dc,f.SkeletonHelper=$O,f.SkeletonHelper2=TI,f.SkinnedMesh=np,f.Source=na,f.Sphere=un,f.SphereGeometry=Ds,f.SphereGeometryGenerator=$I,f.Spherical=pa,f.SphericalHarmonics3=dx,f.SplineCurve=xu,f.SpotLight=zc,f.SpotLight2=Wm,f.SpotLightHelper=YO,f.SpotLightHelper2=PI,f.Sprite=Zf,f.SpriteMaterial=du,f.SrcAlphaFactor=eH,f.SrcAlphaSaturateFactor=aH,f.SrcColorFactor=JV,f.StaticCopyUsage=n5,f.StaticDrawUsage=K4,f.StaticReadUsage=e5,f.StereoCamera=TO,f.StreamCopyUsage=r5,f.StreamDrawUsage=Z4,f.StreamReadUsage=i5,f.StringKeyframeTrack=el,f.SubtractEquation=WV,f.SubtractiveBlending=VV,f.SwitchNodeBasePlugin=Kd,f.TOUCH=MV,f.TYPED_ARRAYS=zx,f.TangentSpaceNormalMap=m4,f.TetrahedronGeometry=Mp,f.Texture=Rt,f.TextureLoader=to,f.ThreeFirstPersonControlsPlugin=E_,f.ThreeSerialization=ke,f.TorusGeometry=$a,f.TorusGeometryGenerator=qI,f.TorusKnotGeometry=Tp,f.TransformAnimationPlugin=U_,f.TransformControls=cr,f.TransformControlsGizmo=MS,f.TransformControlsPlane=TS,f.Triangle=ns,f.TriangleFanDrawMode=d4,f.TriangleStripDrawMode=u4,f.TrianglesDrawMode=h4,f.TubeGeometry=Du,f.TubeGeometryGenerator=ZI,f.TubeShapeGeometry=FM,f.TubeShapeGeometryGenerator=iP,f.TypeSystem=Hr,f.USDZLoadPlugin=M_,f.USDZLoader=iI,f.UVMapping=RH,f.UVsDebug=O1,f.UiConfigMethods=fS,f.UiConfigRenderer=ZU,f.UiConfigRendererBase=pS,f.UiConfigTypeMap=ju,f.Uint16BufferAttribute=Bf,f.Uint32BufferAttribute=QA,f.Uint8BufferAttribute=bD,f.Uint8ClampedBufferAttribute=wD,f.UndoManagerPlugin=Fj,f.Uniform=Up,f.UniformsGroup=WO,f.UniformsLib=Re,f.UniformsUtils=ko,f.UnlitLineMaterial=$n,f.UnlitMaterial=ys,f.UnsignedByteType=KH,f.UnsignedInt248Type=oQ,f.UnsignedInt5999Type=lQ,f.UnsignedIntType=iQ,f.UnsignedShort4444Type=rQ,f.UnsignedShort5551Type=aQ,f.UnsignedShortType=eQ,f.Unzip=oz,f.UnzipInflate=rz,f.UnzipPassThrough=e1,f.Unzlib=cg,f.VSMShadowMap=OV,f.Vector2=$,f.Vector3=x,f.Vector4=rt,f.VectorKeyframeTrack=Za,f.VertexList=p_,f.VertexNode=hI,f.VerticalBlurShader=$S,f.VideoLoader=p1,f.VideoTexture=py,f.VideoTextureLoader=m1,f.ViewHelper2=Uv,f.ViewerUiConfigPlugin=Eg,f.WebGL3DRenderTarget=hD,f.WebGLArrayRenderTarget=cD,f.WebGLCoordinateSystem=l5,f.WebGLCubeRenderTarget=qA,f.WebGLRenderTarget=ps,f.WebGLRenderer=Xf,f.WebGLUtils=mC,f.WebGPUCoordinateSystem=c5,f.Wireframe=L1,f.WireframeGeometry=Ip,f.WireframeGeometry2=f0,f.WireframeGeometry3=ok,f.WrapAroundEnding=o4,f.ZeroCurvatureEnding=r4,f.ZeroFactor=$V,f.ZeroSlopeEnding=a4,f.ZeroStencilOp=M4,f.Zip=nz,f.ZipDeflate=tz,f.ZipLoader=h1,f.ZipPassThrough=Nd,f.Zlib=Q0,f._testFinish=A8,f._testStart=y8,f.absMax=hS,f.addModelProcess=uM,f.aesGcmDecrypt=nS,f.aesGcmEncrypt=iS,f.animate=n0,f.animateAsync=tM,f.animateCameraToViewLinear=nM,f.animateCameraToViewSpherical=iM,f.animateTarget=IN,f.arrayBufferToBase64=Wp,f.assetExportHook=C1,f.autoCenterObject3D=v8,f.autoGPUInstanceMeshes=Iv,f.autoScaleObject3D=_8,f.base64ToArrayBuffer=Qy,f.basicObjectConstraints=Ol,f.bindToValue=Vt,f.blobToDataURL=qp,f.blobToImage=BU,f.buildTextSvg=fM,f.cLinearToRGBM=RN,f.cRGBMToLinear=DN,f.canvasFlipY=Yy,f.centerAllGeometries=c0,f.checkTexMapReference=id,f.clearBit=kU,f.clearCoatTintGLTFExtension=Sh,f.clonePrimitive=ga,f.cloneScriptTag=Gx,f.colorToDataUrl=bU,f.compress=VT,f.compressSync=rg,f.computeMikkTSpaceTangents=FF,f.computeMorphedAttributes=VF,f.computeScreenSpaceBoundingBox=_v,f.convertArrayBufferToStringsInMeta=kv,f.convertStringsToArrayBuffersInMeta=pE,f.copyMaterialUserData=Nv,f.copyObject3DUserData=Sm,f.copyPrimitive=Qu,f.copyProps=$x,f.copyTextureUserData=Fv,f.copyUserData=ad,f.createBindingsProxy=FI,f.createCameraPath=IM,f.createCanvasElement=Nx,f.createCurvePropertyUi=Fg,f.createCurveTypeDropdown=Jd,f.createDiv=Pr,f.createImage=kx,f.createRenderTargetKey=qM,f.createScriptFromURL=uU,f.createShapeFromPreset=z_,f.createStyles=ll,f.css=Qx,f.curveUiConfigs=Ki,f.customBumpMapGLTFExtension=Mh,f.dataTextureFromColor=OF,f.dataTextureFromVec4=UF,f.decompress=KG,f.decompressSync=JG,f.deepAccessObject=Gu,f.deepCloneAttribute=NF,f.defaultObjectProcessor=hM,f.deflate=GT,f.deflateSync=Ud,f.deinterleaveAttribute=fm,f.deinterleaveGeometry=GF,f.deleteObjects=xM,f.downloadBlob=ku,f.downloadFile=jx,f.duplicateObjects=SM,f.embedUrlRefs=cS,f.equalsPrimitive=Hu,f.escapeRegExp=Nu,f.estimateBytesUsed=zF,f.extractAnimationKey=l0,f.filterTopmostAncestors=Ad,f.findLastIndex=Jx,f.fontFormatExtensionMap=dM,f.fragmentClippingGLTFExtension=Ih,f.generateUUID=Ui,f.generateUiConfig=vi,f.generateUiFolder=$p,f.generateValueConfig=ti,f.getComponentTypes=Lh,f.getEmptyMeta=Fr,f.getFileHandle=xU,f.getFilenameFromPath=pU,f.getFittingDistance=xm,f.getKeyByValue=CU,f.getNewFileHandle=SU,f.getOrCall=it,f.getPartialProps=gE,f.getPropDesc=nv,f.getPropertyDescriptor=Xx,f.getTexelDecoding=bv,f.getTexelDecodingFunction=HS,f.getTextureDataType=Sv,f.getTypedArray=Vx,f.getUrlQueryParam=Vu,f.glbEncryptionPreparser=fT,f.glbEncryptionProcessor=dT,f.glsl=ma,f.gunzip=QT,f.gunzipSync=og,f.gzip=VT,f.gzipSync=rg,f.halfFloatToRgbe=VS,f.html=AU,f.htmlDialogWrapper=$U,f.htmlToCanvas=FU,f.htmlToPng=NU,f.htmlToSvg=Ky,f.iCameraCommons=ct,f.iGeometryCommons=ri,f.iLightCommons=pn,f.iMaterialCommons=_e,f.iObjectCommons=Ge,f.imageBitmapToBase64=sS,f.imageBitmapToBlob=PU,f.imageBitmapToCanvas=Xy,f.imageDataToCanvas=DU,f.imageToCanvas=aS,f.imageUrlToImageData=rS,f.includesAll=Kx,f.incrementObjectCloneName=Nm,f.inflate=H0,f.inflateSync=vh,f.interleaveAttributes=kF,f.isInScene=xv,f.isNonRelativeUrl=Hc,f.isPropertyWritable=Yx,f.isWebpExportSupported=RU,f.jsonToBlob=zv,f.lerp=Lm,f.lerpAngle=r0,f.lerpNumber=Jc,f.lerpParams=rM,f.lerpTexture=sM,f.lerpVal=Om,f.lerpVector=o0,f.literalStrings=h8,f.localToWorldQuaternion=qF,f.longestCommonPrefix=gU,f.makeColorSvg=LU,f.makeColorSvgCircle=oS,f.makeGLBFile=bE,f.makeICameraCommonUiConfig=Um,f.makeIObject3DUiConfig=pM,f.makeSamplerUi=Ti,f.makeSetterFor=s0,f.makeTextSvg=OU,f.makeTextSvgAdvanced=kN,f.matDefine=hm,f.matDefineBool=um,f.mergeAttributes=dm,f.mergeBufferAttributes=WF,f.mergeBufferGeometries=jF,f.mergeGeometries=QS,f.mergeGroups=HF,f.mergeResources=v3,f.mergeVertices=jS,f.metaFromResources=Gv,f.metaToResources=od,f.mobileAndTabletCheck=vU,f.noiseBumpMaterialGLTFExtension=Eh,f.now=Mn,f.objectActionsUiConfig=uo,f.objectExtensionsUiConfig=Fm,f.objectHasOwn=qn,f.objectMap=eS,f.objectMap2=Wy,f.onChange=de,f.onChange2=ei,f.onChange3=tt,f.onChangeDispatchEvent=so,f.overrideThreeCache=zS,f.parseFileExtension=Fu,f.pathJoin=zU,f.prettyScrollbar=yU,f.readFile=EU,f.recordUndoCommand=Yp,f.remoteWorkerURL=VU,f.replaceAll=Wn,f.reverseShapeWinding=eP,f.sRGBEncoding=u5,f.safeReplaceString=mU,f.safeSetProperty=an,f.sampleThreepipeViteHmrPlugin=a8,f.serializable=Vc,f.serialize=z,f.serializeTextureInExtras=mE,f.setInnerHTMLWithScripts=dU,f.setPartialProps=Mm,f.setThreeRendererMode=mk,f.setUrlQueryParam=GU,f.setValueUndoCommand=iv,f.setupComponent=oP,f.shaderReplaceString=At,f.shaderUtils=sv,f.snapObject=Pv,f.sortPasses=HM,f.sphericalFromCameraView=a0,f.strFromU8=Fd,f.strToU8=yo,f.svgToCanvas=$y,f.svgToPng=lS,f.svgUrl=jy,f.texImageToCanvas=qS,f.textureDataToImageData=Ev,f.textureToBlob=YF,f.textureToCanvas=pm,f.textureToDataUrl=XF,f.threeConstMappings=Mv,f.threeMaterialInterpolateProps=wa,f.threeMaterialPropList=Et,f.timeout=jn,f.toCamelCase=fU,f.toCreasedNormals=QF,f.toIndexedGeometry=Cv,f.toTitleCase=Hx,f.toTrianglesDrawMode=wv,f.uiButton=lt,f.uiColor=Tn,f.uiConfig=Li,f.uiConfigMaterialExtension=_M,f.uiContainer=rv,f.uiDropdown=Oi,f.uiFolderContainer=gt,f.uiImage=Dr,f.uiInput=Fe,f.uiMonitor=hl,f.uiNumber=Lt,f.uiPanelContainer=Aa,f.uiSlider=Oe,f.uiToggle=ae,f.uiVector=gi,f.uniform=va,f.unzip=lz,f.unzipSync=Y0,f.unzlib=WT,f.unzlibSync=Ea,f.updateBit=Jy,f.updateMaterialDefines=ba,f.updateUi=G_,f.upgradeTexture=bd,f.upgradeWebGLRenderer=NM,f.uploadFile=Wx,f.uuidV4=Zy,f.vLinearToRGBM=oM,f.vRGBMToLinear=aM,f.verifyPermission=IU,f.whiteImageData=mm,f.whiteTexture=gm,f.windowDialogWrapper=uS,f.worldToLocalQuaternion=WS,f.wrapThisFunction=wU,f.wrapThisFunction2=Zx,f.writeFile=TU,f.zip=sz,f.zipSync=hg,f.zlib=YG,f.zlibSync=lg,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
//# sourceMappingURL=index.js.map
