@xeokit/xeokit-sdk 2.4.2-beta-20 → 2.4.2-beta-21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class s{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class n{constructor(){this.items=[]}}class i{constructor(e,t,s,n,i){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=n,this.getShown=i,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let a=!0,r=a?Float64Array:Float32Array;const l=new r(3),o=new r(16),c=new r(16),u=new r(4),h={setDoublePrecisionEnabled(e){a=e,r=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new r(e||2),vec3:e=>new r(e||3),vec4:e=>new r(e||4),mat3:e=>new r(e||9),mat3ToMat4:(e,t=new r(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new r(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const n=new r(2);for(let i=0,a=e.length;i<a;i++)h.splitDouble(e[i],n),t[i]=n[0],s[i]=n[1]},splitDouble(e,t){const s=r.from([e])[0],n=e-s;t[0]=s,t[1]=n},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&n|128]}${e[n>>8&255]}-${e[n>>16&255]}${e[n>>24&255]}${e[255&i]}${e[i>>8&255]}${e[i>>16&255]}${e[i>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new r(e[0]);for(let s=1;s<e.length;s++)t[0]+=e[s][0],t[1]+=e[s][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],n=e[1],i=e[2],a=t[0],r=t[1],l=t[2];return[n*l-i*r,i*a-s*l,s*r-n*a,0]},cross3Vec3(e,t,s){s||(s=e);const n=e[0],i=e[1],a=e[2],r=t[0],l=t[1],o=t[2];return s[0]=i*o-a*l,s[1]=a*r-n*o,s[2]=n*l-i*r,s},sqLenVec4:e=>h.dotVec4(e,e),lenVec4:e=>Math.sqrt(h.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>h.dotVec3(e,e),sqLenVec2:e=>h.dotVec2(e,e),lenVec3:e=>Math.sqrt(h.sqLenVec3(e)),distVec3:(()=>{const e=new r(3);return(t,s)=>h.lenVec3(h.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(h.sqLenVec2(e)),distVec2:(()=>{const e=new r(2);return(t,s)=>h.lenVec2(h.subVec2(t,s,e))})(),rcpVec3:(e,t)=>h.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/h.lenVec4(e);return h.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/h.lenVec3(e);return h.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/h.lenVec2(e);return h.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=h.dotVec3(e,t)/Math.sqrt(h.sqLenVec3(e)*h.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new r(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=h.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=h.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=h.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,n=(t=Array.prototype.slice.call(t)).length;s<n;s++)t[s]=e(t[s]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||h.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>h.m4s(0),setMat4ToOnes:()=>h.m4s(1),diagonalMat4v:e=>new r([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,n)=>h.diagonalMat4v([e,t,s,n]),diagonalMat4s:e=>h.diagonalMat4c(e,e,e,e),identityMat4:(e=new r(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new r(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>h.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const n=e[0],i=e[1],a=e[2],r=e[3],l=e[4],o=e[5],c=e[6],u=e[7],h=e[8],p=e[9],A=e[10],d=e[11],f=e[12],I=e[13],y=e[14],m=e[15],v=t[0],w=t[1],g=t[2],E=t[3],T=t[4],b=t[5],D=t[6],P=t[7],R=t[8],C=t[9],_=t[10],B=t[11],O=t[12],S=t[13],N=t[14],x=t[15];return s[0]=v*n+w*l+g*h+E*f,s[1]=v*i+w*o+g*p+E*I,s[2]=v*a+w*c+g*A+E*y,s[3]=v*r+w*u+g*d+E*m,s[4]=T*n+b*l+D*h+P*f,s[5]=T*i+b*o+D*p+P*I,s[6]=T*a+b*c+D*A+P*y,s[7]=T*r+b*u+D*d+P*m,s[8]=R*n+C*l+_*h+B*f,s[9]=R*i+C*o+_*p+B*I,s[10]=R*a+C*c+_*A+B*y,s[11]=R*r+C*u+_*d+B*m,s[12]=O*n+S*l+N*h+x*f,s[13]=O*i+S*o+N*p+x*I,s[14]=O*a+S*c+N*A+x*y,s[15]=O*r+S*u+N*d+x*m,s},mulMat3(e,t,s){s||(s=new r(9));const n=e[0],i=e[3],a=e[6],l=e[1],o=e[4],c=e[7],u=e[2],h=e[5],p=e[8],A=t[0],d=t[3],f=t[6],I=t[1],y=t[4],m=t[7],v=t[2],w=t[5],g=t[8];return s[0]=n*A+i*I+a*v,s[3]=n*d+i*y+a*w,s[6]=n*f+i*m+a*g,s[1]=l*A+o*I+c*v,s[4]=l*d+o*y+c*w,s[7]=l*f+o*m+c*g,s[2]=u*A+h*I+p*v,s[5]=u*d+h*y+p*w,s[8]=u*f+h*m+p*g,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=h.vec4()){const n=t[0],i=t[1],a=t[2],r=t[3];return s[0]=e[0]*n+e[4]*i+e[8]*a+e[12]*r,s[1]=e[1]*n+e[5]*i+e[9]*a+e[13]*r,s[2]=e[2]*n+e[6]*i+e[10]*a+e[14]*r,s[3]=e[3]*n+e[7]*i+e[11]*a+e[15]*r,s},transposeMat4(e,t){const s=e[4],n=e[14],i=e[8],a=e[13],r=e[12],l=e[9];if(!t||e===t){const t=e[1],o=e[2],c=e[3],u=e[6],h=e[7],p=e[11];return e[1]=s,e[2]=i,e[3]=r,e[4]=t,e[6]=l,e[7]=a,e[8]=o,e[9]=u,e[11]=n,e[12]=c,e[13]=h,e[14]=p,e}return t[0]=e[0],t[1]=s,t[2]=i,t[3]=r,t[4]=e[1],t[5]=e[5],t[6]=l,t[7]=a,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=n,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=n,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],s=e[1],n=e[2],i=e[3],a=e[4],r=e[5],l=e[6],o=e[7],c=e[8],u=e[9],h=e[10],p=e[11],A=e[12],d=e[13],f=e[14],I=e[15];return A*u*l*i-c*d*l*i-A*r*h*i+a*d*h*i+c*r*f*i-a*u*f*i-A*u*n*o+c*d*n*o+A*s*h*o-t*d*h*o-c*s*f*o+t*u*f*o+A*r*n*p-a*d*n*p-A*s*l*p+t*d*l*p+a*s*f*p-t*r*f*p-c*r*n*I+a*u*n*I+c*s*l*I-t*u*l*I-a*s*h*I+t*r*h*I},inverseMat4(e,t){t||(t=e);const s=e[0],n=e[1],i=e[2],a=e[3],r=e[4],l=e[5],o=e[6],c=e[7],u=e[8],h=e[9],p=e[10],A=e[11],d=e[12],f=e[13],I=e[14],y=e[15],m=s*l-n*r,v=s*o-i*r,w=s*c-a*r,g=n*o-i*l,E=n*c-a*l,T=i*c-a*o,b=u*f-h*d,D=u*I-p*d,P=u*y-A*d,R=h*I-p*f,C=h*y-A*f,_=p*y-A*I,B=1/(m*_-v*C+w*R+g*P-E*D+T*b);return t[0]=(l*_-o*C+c*R)*B,t[1]=(-n*_+i*C-a*R)*B,t[2]=(f*T-I*E+y*g)*B,t[3]=(-h*T+p*E-A*g)*B,t[4]=(-r*_+o*P-c*D)*B,t[5]=(s*_-i*P+a*D)*B,t[6]=(-d*T+I*w-y*v)*B,t[7]=(u*T-p*w+A*v)*B,t[8]=(r*C-l*P+c*b)*B,t[9]=(-s*C+n*P-a*b)*B,t[10]=(d*E-f*w+y*m)*B,t[11]=(-u*E+h*w-A*m)*B,t[12]=(-r*R+l*D-o*b)*B,t[13]=(s*R-n*D+i*b)*B,t[14]=(-d*g+f*v-I*m)*B,t[15]=(u*g-h*v+p*m)*B,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||h.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||h.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new r(3);return(t,s,n,i)=>(e[0]=t,e[1]=s,e[2]=n,h.translationMat4v(e,i))})(),translationMat4s:(e,t)=>h.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>h.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,n){const i=n[3];n[0]+=i*e,n[1]+=i*t,n[2]+=i*s;const a=n[7];n[4]+=a*e,n[5]+=a*t,n[6]+=a*s;const r=n[11];n[8]+=r*e,n[9]+=r*t,n[10]+=r*s;const l=n[15];return n[12]+=l*e,n[13]+=l*t,n[14]+=l*s,n},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const n=h.normalizeVec4([t[0],t[1],t[2],0],[]),i=Math.sin(e),a=Math.cos(e),r=1-a,l=n[0],o=n[1],c=n[2];let u,p,A,d,f,I;return u=l*o,p=o*c,A=c*l,d=l*i,f=o*i,I=c*i,(s=s||h.mat4())[0]=r*l*l+a,s[1]=r*u+I,s[2]=r*A-f,s[3]=0,s[4]=r*u-I,s[5]=r*o*o+a,s[6]=r*p+d,s[7]=0,s[8]=r*A+f,s[9]=r*p-d,s[10]=r*c*c+a,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,n,i)=>h.rotationMat4v(e,[t,s,n],i),scalingMat4v:(e,t=h.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=h.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new r(3);return(t,s,n,i)=>(e[0]=t,e[1]=s,e[2]=n,h.scalingMat4v(e,i))})(),scaleMat4c:(e,t,s,n)=>(n[0]*=e,n[4]*=t,n[8]*=s,n[1]*=e,n[5]*=t,n[9]*=s,n[2]*=e,n[6]*=t,n[10]*=s,n[3]*=e,n[7]*=t,n[11]*=s,n),scaleMat4v(e,t){const s=e[0],n=e[1],i=e[2];return t[0]*=s,t[4]*=n,t[8]*=i,t[1]*=s,t[5]*=n,t[9]*=i,t[2]*=s,t[6]*=n,t[10]*=i,t[3]*=s,t[7]*=n,t[11]*=i,t},scalingMat4s:e=>h.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=h.mat4()){const n=e[0],i=e[1],a=e[2],r=e[3],l=n+n,o=i+i,c=a+a,u=n*l,p=n*o,A=n*c,d=i*o,f=i*c,I=a*c,y=r*l,m=r*o,v=r*c;return s[0]=1-(d+I),s[1]=p+v,s[2]=A-m,s[3]=0,s[4]=p-v,s[5]=1-(u+I),s[6]=f+y,s[7]=0,s[8]=A+m,s[9]=f-y,s[10]=1-(u+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=h.vec4()){const n=h.clamp,i=e[0],a=e[4],r=e[8],l=e[1],o=e[5],c=e[9],u=e[2],p=e[6],A=e[10];return"XYZ"===t?(s[1]=Math.asin(n(r,-1,1)),Math.abs(r)<.99999?(s[0]=Math.atan2(-c,A),s[2]=Math.atan2(-a,i)):(s[0]=Math.atan2(p,o),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-n(c,-1,1)),Math.abs(c)<.99999?(s[1]=Math.atan2(r,A),s[2]=Math.atan2(l,o)):(s[1]=Math.atan2(-u,i),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(n(p,-1,1)),Math.abs(p)<.99999?(s[1]=Math.atan2(-u,A),s[2]=Math.atan2(-a,o)):(s[1]=0,s[2]=Math.atan2(l,i))):"ZYX"===t?(s[1]=Math.asin(-n(u,-1,1)),Math.abs(u)<.99999?(s[0]=Math.atan2(p,A),s[2]=Math.atan2(l,i)):(s[0]=0,s[2]=Math.atan2(-a,o))):"YZX"===t?(s[2]=Math.asin(n(l,-1,1)),Math.abs(l)<.99999?(s[0]=Math.atan2(-c,o),s[1]=Math.atan2(-u,i)):(s[0]=0,s[1]=Math.atan2(r,A))):"XZY"===t&&(s[2]=Math.asin(-n(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(p,o),s[1]=Math.atan2(r,i)):(s[0]=Math.atan2(-c,A),s[1]=0)),s},composeMat4:(e,t,s,n=h.mat4())=>(h.quaternionToRotationMat4(t,n),h.scaleMat4v(s,n),h.translateMat4v(e,n),n),decomposeMat4:(()=>{const e=new r(3),t=new r(16);return function(s,n,i,a){e[0]=s[0],e[1]=s[1],e[2]=s[2];let r=h.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const l=h.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const o=h.lenVec3(e);h.determinantMat4(s)<0&&(r=-r),n[0]=s[12],n[1]=s[13],n[2]=s[14],t.set(s);const c=1/r,u=1/l,p=1/o;return t[0]*=c,t[1]*=c,t[2]*=c,t[4]*=u,t[5]*=u,t[6]*=u,t[8]*=p,t[9]*=p,t[10]*=p,h.mat4ToQuaternion(t,i),a[0]=r,a[1]=l,a[2]=o,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,n){n||(n=h.mat4());const i=e[0],a=e[1],r=e[2],l=s[0],o=s[1],c=s[2],u=t[0],p=t[1],A=t[2];if(i===u&&a===p&&r===A)return h.identityMat4();let d,f,I,y,m,v,w,g,E,T;return d=i-u,f=a-p,I=r-A,T=1/Math.sqrt(d*d+f*f+I*I),d*=T,f*=T,I*=T,y=o*I-c*f,m=c*d-l*I,v=l*f-o*d,T=Math.sqrt(y*y+m*m+v*v),T?(T=1/T,y*=T,m*=T,v*=T):(y=0,m=0,v=0),w=f*v-I*m,g=I*y-d*v,E=d*m-f*y,T=Math.sqrt(w*w+g*g+E*E),T?(T=1/T,w*=T,g*=T,E*=T):(w=0,g=0,E=0),n[0]=y,n[1]=w,n[2]=d,n[3]=0,n[4]=m,n[5]=g,n[6]=f,n[7]=0,n[8]=v,n[9]=E,n[10]=I,n[11]=0,n[12]=-(y*i+m*a+v*r),n[13]=-(w*i+g*a+E*r),n[14]=-(d*i+f*a+I*r),n[15]=1,n},lookAtMat4c:(e,t,s,n,i,a,r,l,o)=>h.lookAtMat4v([e,t,s],[n,i,a],[r,l,o],[]),orthoMat4c(e,t,s,n,i,a,r){r||(r=h.mat4());const l=t-e,o=n-s,c=a-i;return r[0]=2/l,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=2/o,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=-2/c,r[11]=0,r[12]=-(e+t)/l,r[13]=-(n+s)/o,r[14]=-(a+i)/c,r[15]=1,r},frustumMat4v(e,t,s){s||(s=h.mat4());const n=[e[0],e[1],e[2],0],i=[t[0],t[1],t[2],0];h.addVec4(i,n,o),h.subVec4(i,n,c);const a=2*n[2],r=c[0],l=c[1],u=c[2];return s[0]=a/r,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=a/l,s[6]=0,s[7]=0,s[8]=o[0]/r,s[9]=o[1]/l,s[10]=-o[2]/u,s[11]=-1,s[12]=0,s[13]=0,s[14]=-a*i[2]/u,s[15]=0,s},frustumMat4(e,t,s,n,i,a,r){r||(r=h.mat4());const l=t-e,o=n-s,c=a-i;return r[0]=2*i/l,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=2*i/o,r[6]=0,r[7]=0,r[8]=(t+e)/l,r[9]=(n+s)/o,r[10]=-(a+i)/c,r[11]=-1,r[12]=0,r[13]=0,r[14]=-a*i*2/c,r[15]=0,r},perspectiveMat4(e,t,s,n,i){const a=[],r=[];return a[2]=s,r[2]=n,r[1]=a[2]*Math.tan(e/2),a[1]=-r[1],r[0]=r[1]*t,a[0]=-r[0],h.frustumMat4v(a,r,i)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,s=h.vec3()){const n=t[0],i=t[1],a=t[2];return s[0]=e[0]*n+e[4]*i+e[8]*a+e[12],s[1]=e[1]*n+e[5]*i+e[9]*a+e[13],s[2]=e[2]*n+e[6]*i+e[10]*a+e[14],s},transformPoint4:(e,t,s=h.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const n=s||[],i=t.length;let a,r,l,o;const c=e[0],u=e[1],h=e[2],p=e[3],A=e[4],d=e[5],f=e[6],I=e[7],y=e[8],m=e[9],v=e[10],w=e[11],g=e[12],E=e[13],T=e[14],b=e[15];let D;for(let e=0;e<i;++e)o=t[e],a=o[0],r=o[1],l=o[2],D=n[e]||(n[e]=[0,0,0]),D[0]=c*a+A*r+y*l+g,D[1]=u*a+d*r+m*l+E,D[2]=h*a+f*r+v*l+T,D[3]=p*a+I*r+w*l+b;return n.length=i,n},transformPositions3(e,t,s=t){let n;const i=t.length;let a,r,l;const o=e[0],c=e[1],u=e[2];e[3];const h=e[4],p=e[5],A=e[6];e[7];const d=e[8],f=e[9],I=e[10];e[11];const y=e[12],m=e[13],v=e[14];for(e[15],n=0;n<i;n+=3)a=t[n+0],r=t[n+1],l=t[n+2],s[n+0]=o*a+h*r+d*l+y,s[n+1]=c*a+p*r+f*l+m,s[n+2]=u*a+A*r+I*l+v;return s},transformPositions4(e,t,s=t){let n;const i=t.length;let a,r,l;const o=e[0],c=e[1],u=e[2],h=e[3],p=e[4],A=e[5],d=e[6],f=e[7],I=e[8],y=e[9],m=e[10],v=e[11],w=e[12],g=e[13],E=e[14],T=e[15];for(n=0;n<i;n+=4)a=t[n+0],r=t[n+1],l=t[n+2],s[n+0]=o*a+p*r+I*l+w,s[n+1]=c*a+A*r+y*l+g,s[n+2]=u*a+d*r+m*l+E,s[n+3]=h*a+f*r+v*l+T;return s},transformVec3(e,t,s){const n=t[0],i=t[1],a=t[2];return(s=s||this.vec3())[0]=e[0]*n+e[4]*i+e[8]*a,s[1]=e[1]*n+e[5]*i+e[9]*a,s[2]=e[2]*n+e[6]*i+e[10]*a,s},transformVec4(e,t,s){const n=t[0],i=t[1],a=t[2],r=t[3];return(s=s||h.vec4())[0]=e[0]*n+e[4]*i+e[8]*a+e[12]*r,s[1]=e[1]*n+e[5]*i+e[9]*a+e[13]*r,s[2]=e[2]*n+e[6]*i+e[10]*a+e[14]*r,s[3]=e[3]*n+e[7]*i+e[11]*a+e[15]*r,s},rotateVec2(e,t,s,n=e){const i=Math.cos(s),a=Math.sin(s),r=e[0]-t[0],l=e[1]-t[1];return n[0]=r*i-l*a+t[0],n[1]=r*a+l*i+t[1],e},rotateVec3X(e,t,s,n){const i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0],a[1]=i[1]*Math.cos(s)-i[2]*Math.sin(s),a[2]=i[1]*Math.sin(s)+i[2]*Math.cos(s),n[0]=a[0]+t[0],n[1]=a[1]+t[1],n[2]=a[2]+t[2],n},rotateVec3Y(e,t,s,n){const i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[2]*Math.sin(s)+i[0]*Math.cos(s),a[1]=i[1],a[2]=i[2]*Math.cos(s)-i[0]*Math.sin(s),n[0]=a[0]+t[0],n[1]=a[1]+t[1],n[2]=a[2]+t[2],n},rotateVec3Z(e,t,s,n){const i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0]*Math.cos(s)-i[1]*Math.sin(s),a[1]=i[0]*Math.sin(s)+i[1]*Math.cos(s),a[2]=i[2],n[0]=a[0]+t[0],n[1]=a[1]+t[1],n[2]=a[2]+t[2],n},projectVec4(e,t){const s=1/e[3];return(t=t||h.vec2())[0]=e[0]*s,t[1]=e[1]*s,t},unprojectVec3:(()=>{const e=new r(16),t=new r(16),s=new r(16);return function(n,i,a,r){return this.transformVec3(this.mulMat4(this.inverseMat4(i,e),this.inverseMat4(a,t),s),n,r)}})(),lerpVec3(e,t,s,n,i,a){const r=a||h.vec3(),l=(e-t)/(s-t);return r[0]=n[0]+l*(i[0]-n[0]),r[1]=n[1]+l*(i[1]-n[1]),r[2]=n[2]+l*(i[2]-n[2]),r},lerpMat4(e,t,s,n,i,a){const r=a||h.mat4(),l=(e-t)/(s-t);return r[0]=n[0]+l*(i[0]-n[0]),r[1]=n[1]+l*(i[1]-n[1]),r[2]=n[2]+l*(i[2]-n[2]),r[3]=n[3]+l*(i[3]-n[3]),r[4]=n[4]+l*(i[4]-n[4]),r[5]=n[5]+l*(i[5]-n[5]),r[6]=n[6]+l*(i[6]-n[6]),r[7]=n[7]+l*(i[7]-n[7]),r[8]=n[8]+l*(i[8]-n[8]),r[9]=n[9]+l*(i[9]-n[9]),r[10]=n[10]+l*(i[10]-n[10]),r[11]=n[11]+l*(i[11]-n[11]),r[12]=n[12]+l*(i[12]-n[12]),r[13]=n[13]+l*(i[13]-n[13]),r[14]=n[14]+l*(i[14]-n[14]),r[15]=n[15]+l*(i[15]-n[15]),r},flatten(e){const t=[];let s,n,i,a,r;for(s=0,n=e.length;s<n;s++)for(r=e[s],i=0,a=r.length;i<a;i++)t.push(r[i]);return t},identityQuaternion:(e=h.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=h.vec4()){const n=e[0]*h.DEGTORAD/2,i=e[1]*h.DEGTORAD/2,a=e[2]*h.DEGTORAD/2,r=Math.cos(n),l=Math.cos(i),o=Math.cos(a),c=Math.sin(n),u=Math.sin(i),p=Math.sin(a);return"XYZ"===t?(s[0]=c*l*o+r*u*p,s[1]=r*u*o-c*l*p,s[2]=r*l*p+c*u*o,s[3]=r*l*o-c*u*p):"YXZ"===t?(s[0]=c*l*o+r*u*p,s[1]=r*u*o-c*l*p,s[2]=r*l*p-c*u*o,s[3]=r*l*o+c*u*p):"ZXY"===t?(s[0]=c*l*o-r*u*p,s[1]=r*u*o+c*l*p,s[2]=r*l*p+c*u*o,s[3]=r*l*o-c*u*p):"ZYX"===t?(s[0]=c*l*o-r*u*p,s[1]=r*u*o+c*l*p,s[2]=r*l*p-c*u*o,s[3]=r*l*o+c*u*p):"YZX"===t?(s[0]=c*l*o+r*u*p,s[1]=r*u*o+c*l*p,s[2]=r*l*p-c*u*o,s[3]=r*l*o-c*u*p):"XZY"===t&&(s[0]=c*l*o-r*u*p,s[1]=r*u*o-c*l*p,s[2]=r*l*p+c*u*o,s[3]=r*l*o+c*u*p),s},mat4ToQuaternion(e,t=h.vec4()){const s=e[0],n=e[4],i=e[8],a=e[1],r=e[5],l=e[9],o=e[2],c=e[6],u=e[10];let p;const A=s+r+u;return A>0?(p=.5/Math.sqrt(A+1),t[3]=.25/p,t[0]=(c-l)*p,t[1]=(i-o)*p,t[2]=(a-n)*p):s>r&&s>u?(p=2*Math.sqrt(1+s-r-u),t[3]=(c-l)/p,t[0]=.25*p,t[1]=(n+a)/p,t[2]=(i+o)/p):r>u?(p=2*Math.sqrt(1+r-s-u),t[3]=(i-o)/p,t[0]=(n+a)/p,t[1]=.25*p,t[2]=(l+c)/p):(p=2*Math.sqrt(1+u-s-r),t[3]=(a-n)/p,t[0]=(i+o)/p,t[1]=(l+c)/p,t[2]=.25*p),t},vec3PairToQuaternion(e,t,s=h.vec4()){const n=Math.sqrt(h.dotVec3(e,e)*h.dotVec3(t,t));let i=n+h.dotVec3(e,t);return i<1e-8*n?(i=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):h.cross3Vec3(e,t,s),s[3]=i,h.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=h.vec4()){const s=e[3]/2,n=Math.sin(s);return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new r(16);return(t,s,n)=>(n=n||h.vec3(),h.quaternionToRotationMat4(t,e),h.mat4ToEuler(e,s,n),n)})(),mulQuaternions(e,t,s=h.vec4()){const n=e[0],i=e[1],a=e[2],r=e[3],l=t[0],o=t[1],c=t[2],u=t[3];return s[0]=r*l+n*u+i*c-a*o,s[1]=r*o+i*u+a*l-n*c,s[2]=r*c+a*u+n*o-i*l,s[3]=r*u-n*l-i*o-a*c,s},vec3ApplyQuaternion(e,t,s=h.vec3()){const n=t[0],i=t[1],a=t[2],r=e[0],l=e[1],o=e[2],c=e[3],u=c*n+l*a-o*i,p=c*i+o*n-r*a,A=c*a+r*i-l*n,d=-r*n-l*i-o*a;return s[0]=u*c+d*-r+p*-o-A*-l,s[1]=p*c+d*-l+A*-r-u*-o,s[2]=A*c+d*-o+u*-l-p*-r,s},quaternionToMat4(e,t){t=h.identityMat4(t);const s=e[0],n=e[1],i=e[2],a=e[3],r=2*s,l=2*n,o=2*i,c=r*a,u=l*a,p=o*a,A=r*s,d=l*s,f=o*s,I=l*n,y=o*n,m=o*i;return t[0]=1-(I+m),t[1]=d+p,t[2]=f-u,t[4]=d-p,t[5]=1-(A+m),t[6]=y+c,t[8]=f+u,t[9]=y-c,t[10]=1-(A+I),t},quaternionToRotationMat4(e,t){const s=e[0],n=e[1],i=e[2],a=e[3],r=s+s,l=n+n,o=i+i,c=s*r,u=s*l,h=s*o,p=n*l,A=n*o,d=i*o,f=a*r,I=a*l,y=a*o;return t[0]=1-(p+d),t[4]=u-y,t[8]=h+I,t[1]=u+y,t[5]=1-(c+d),t[9]=A-f,t[2]=h-I,t[6]=A+f,t[10]=1-(c+p),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=h.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>h.normalizeQuaternion(h.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=h.vec4()){const s=(e=h.normalizeQuaternion(e,u))[3],n=2*Math.acos(s),i=Math.sqrt(1-s*s);return i<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i),t[3]=n,t},AABB3:e=>new r(e||6),AABB2:e=>new r(e||4),OBB3:e=>new r(e||32),OBB2:e=>new r(e||16),Sphere3:(e,t,s,n)=>new r([e,t,s,n]),transformOBB3(e,t,s=t){let n;const i=t.length;let a,r,l;const o=e[0],c=e[1],u=e[2],h=e[3],p=e[4],A=e[5],d=e[6],f=e[7],I=e[8],y=e[9],m=e[10],v=e[11],w=e[12],g=e[13],E=e[14],T=e[15];for(n=0;n<i;n+=4)a=t[n+0],r=t[n+1],l=t[n+2],s[n+0]=o*a+p*r+I*l+w,s[n+1]=c*a+A*r+y*l+g,s[n+2]=u*a+d*r+m*l+E,s[n+3]=h*a+f*r+v*l+T;return s},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new r(3),t=new r(3),s=new r(3);return n=>(e[0]=n[0],e[1]=n[1],e[2]=n[2],t[0]=n[3],t[1]=n[4],t[2]=n[5],h.subVec3(t,e,s),Math.abs(h.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new r(3),t=new r(3),s=new r(3);return(n,i)=>{e[0]=n[0],e[1]=n[1],e[2]=n[2],t[0]=n[3],t[1]=n[4],t[2]=n[5];const a=h.subVec3(t,e,s),r=i[0]-n[0],l=n[3]-i[0],o=i[1]-n[1],c=n[4]-i[1],u=i[2]-n[2],p=n[5]-i[2];return a[0]+=r>l?r:l,a[1]+=o>c?o:c,a[2]+=u>p?u:p,Math.abs(h.lenVec3(a))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||h.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||h.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=h.AABB3())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MAX_DOUBLE,e[3]=h.MIN_DOUBLE,e[4]=h.MIN_DOUBLE,e[5]=h.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=h.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new r(3);return(t,s,n)=>{s=s||h.AABB3();let i,a,r,l=h.MAX_DOUBLE,o=h.MAX_DOUBLE,c=h.MAX_DOUBLE,u=h.MIN_DOUBLE,p=h.MIN_DOUBLE,A=h.MIN_DOUBLE;for(let s=0,d=t.length;s<d;s+=3)n?(e[0]=t[s+0],e[1]=t[s+1],e[2]=t[s+2],h.decompressPosition(e,n,e),i=e[0],a=e[1],r=e[2]):(i=t[s+0],a=t[s+1],r=t[s+2]),i<l&&(l=i),a<o&&(o=a),r<c&&(c=r),i>u&&(u=i),a>p&&(p=a),r>A&&(A=r);return s[0]=l,s[1]=o,s[2]=c,s[3]=u,s[4]=p,s[5]=A,s}})(),OBB3ToAABB3(e,t=h.AABB3()){let s,n,i,a=h.MAX_DOUBLE,r=h.MAX_DOUBLE,l=h.MAX_DOUBLE,o=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)s=e[t+0],n=e[t+1],i=e[t+2],s<a&&(a=s),n<r&&(r=n),i<l&&(l=i),s>o&&(o=s),n>c&&(c=n),i>u&&(u=i);return t[0]=a,t[1]=r,t[2]=l,t[3]=o,t[4]=c,t[5]=u,t},points3ToAABB3(e,t=h.AABB3()){let s,n,i,a=h.MAX_DOUBLE,r=h.MAX_DOUBLE,l=h.MAX_DOUBLE,o=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)s=e[t][0],n=e[t][1],i=e[t][2],s<a&&(a=s),n<r&&(r=n),i<l&&(l=i),s>o&&(o=s),n>c&&(c=n),i>u&&(u=i);return t[0]=a,t[1]=r,t[2]=l,t[3]=o,t[4]=c,t[5]=u,t},points3ToSphere3:(()=>{const e=new r(3);return(t,s)=>{s=s||h.vec4();let n,i=0,a=0,r=0;const l=t.length;for(n=0;n<l;n++)i+=t[n][0],a+=t[n][1],r+=t[n][2];s[0]=i/l,s[1]=a/l,s[2]=r/l;let o,c=0;for(n=0;n<l;n++)o=Math.abs(h.lenVec3(h.subVec3(t[n],s,e))),o>c&&(c=o);return s[3]=c,s}})(),positions3ToSphere3:(()=>{const e=new r(3),t=new r(3);return(s,n)=>{n=n||h.vec4();let i,a=0,r=0,l=0;const o=s.length;let c=0;for(i=0;i<o;i+=3)a+=s[i],r+=s[i+1],l+=s[i+2];const u=o/3;let p;for(n[0]=a/u,n[1]=r/u,n[2]=l/u,i=0;i<o;i+=3)e[0]=s[i],e[1]=s[i+1],e[2]=s[i+2],p=Math.abs(h.lenVec3(h.subVec3(e,n,t))),p>c&&(c=p);return n[3]=c,n}})(),OBB3ToSphere3:(()=>{const e=new r(3),t=new r(3);return(s,n)=>{n=n||h.vec4();let i,a=0,r=0,l=0;const o=s.length,c=o/4;for(i=0;i<o;i+=4)a+=s[i+0],r+=s[i+1],l+=s[i+2];n[0]=a/c,n[1]=r/c,n[2]=l/c;let u,p=0;for(i=0;i<o;i+=4)e[0]=s[i+0],e[1]=s[i+1],e[2]=s[i+2],u=Math.abs(h.lenVec3(h.subVec3(e,n,t))),u>p&&(p=u);return n[3]=p,n}})(),getSphere3Center:(e,t=h.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=h.vec3()){let s=0,n=0,i=0;for(var a=0,r=e.length;a<r;a+=3)s+=e[a+0],n+=e[a+1],i+=e[a+2];const l=e.length/3;return t[0]=s/l,t[1]=n/l,t[2]=i/l,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var s,n,i,a=0,r=t.length;a<r;a+=3)s=t[a],n=t[a+1],i=t[a+2],e[0]>s&&(e[0]=s),e[1]>n&&(e[1]=n),e[2]>i&&(e[2]=i),e[3]<s&&(e[3]=s),e[4]<n&&(e[4]=n),e[5]<i&&(e[5]=i);return e},collapseAABB2:(e=h.AABB2())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MIN_DOUBLE,e[3]=h.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],planeAABB3Intersect(e,t,s){let n,i;e[0]>0?(n=e[0]*s[0],i=e[0]*s[3]):(n=e[0]*s[3],i=e[0]*s[0]),e[1]>0?(n+=e[1]*s[1],i+=e[1]*s[4]):(n+=e[1]*s[4],i+=e[1]*s[1]),e[2]>0?(n+=e[2]*s[2],i+=e[2]*s[5]):(n+=e[2]*s[5],i+=e[2]*s[2]);if(n<=-t&&i<=-t)return-1;return n>=-t&&i>=-t?1:0},OBB3ToAABB2(e,t=h.AABB2()){let s,n,i,a,r=h.MAX_DOUBLE,l=h.MAX_DOUBLE,o=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,u=e.length;t<u;t+=4)s=e[t+0],n=e[t+1],i=e[t+3]||1,a=1/i,s*=a,n*=a,s<r&&(r=s),n<l&&(l=n),s>o&&(o=s),n>c&&(c=n);return t[0]=r,t[1]=l,t[2]=o,t[3]=c,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,s,n=e){const i=.5*(e[0]+1),a=.5*(e[1]+1),r=.5*(e[2]+1),l=.5*(e[3]+1);return n[0]=Math.floor(i*t),n[1]=s-Math.floor(l*s),n[2]=Math.floor(r*t),n[3]=s-Math.floor(a*s),n},tangentQuadraticBezier:(e,t,s,n)=>2*(1-e)*(s-t)+2*e*(n-s),tangentQuadraticBezier3:(e,t,s,n,i)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*n*(1-e)-3*e*e*n+3*e*e*i,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,s,n,i){const a=.5*(s-e),r=.5*(n-t),l=i*i;return(2*t-2*s+a+r)*(i*l)+(-3*t+3*s-2*a-r)*l+a*i+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,n){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,n)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,n,i){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,n)+this.b3p3(e,i)},triangleNormal(e,t,s,n=h.vec3()){const i=t[0]-e[0],a=t[1]-e[1],r=t[2]-e[2],l=s[0]-e[0],o=s[1]-e[1],c=s[2]-e[2],u=a*c-r*o,p=r*l-i*c,A=i*o-a*l,d=Math.sqrt(u*u+p*p+A*A);return 0===d?(n[0]=0,n[1]=0,n[2]=0):(n[0]=u/d,n[1]=p/d,n[2]=A/d),n},rayTriangleIntersect:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3),i=new r(3);return(a,r,l,o,c,u)=>{u=u||h.vec3();const p=h.subVec3(o,l,e),A=h.subVec3(c,l,t),d=h.cross3Vec3(r,A,s),f=h.dotVec3(p,d);if(f<1e-6)return null;const I=h.subVec3(a,l,n),y=h.dotVec3(I,d);if(y<0||y>f)return null;const m=h.cross3Vec3(I,p,i),v=h.dotVec3(r,m);if(v<0||y+v>f)return null;const w=h.dotVec3(A,m)/f;return u[0]=a[0]+w*r[0],u[1]=a[1]+w*r[1],u[2]=a[2]+w*r[2],u}})(),rayPlaneIntersect:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3);return(i,a,r,l,o,c)=>{c=c||h.vec3(),a=h.normalizeVec3(a,e);const u=h.subVec3(l,r,t),p=h.subVec3(o,r,s),A=h.cross3Vec3(u,p,n);h.normalizeVec3(A,A);const d=-h.dotVec3(r,A),f=-(h.dotVec3(i,A)+d)/h.dotVec3(a,A);return c[0]=i[0]+f*a[0],c[1]=i[1]+f*a[1],c[2]=i[2]+f*a[2],c}})(),cartesianToBarycentric:(()=>{const e=new r(3),t=new r(3),s=new r(3);return(n,i,a,r,l)=>{const o=h.subVec3(r,i,e),c=h.subVec3(a,i,t),u=h.subVec3(n,i,s),p=h.dotVec3(o,o),A=h.dotVec3(o,c),d=h.dotVec3(o,u),f=h.dotVec3(c,c),I=h.dotVec3(c,u),y=p*f-A*A;if(0===y)return null;const m=1/y,v=(f*d-A*I)*m,w=(p*I-A*d)*m;return l[0]=1-v-w,l[1]=w,l[2]=v,l}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,n,i=h.vec3()){const a=e[0],r=e[1],l=e[2];return i[0]=t[0]*a+s[0]*r+n[0]*l,i[1]=t[1]*a+s[1]*r+n[1]*l,i[2]=t[2]*a+s[2]*r+n[2]*l,i},mergeVertices(e,t,s,n){const i={},a=[],r=[],l=t?[]:null,o=s?[]:null,c=[];let u,h,p,A;const d=1e4;let f,I,y=0;for(f=0,I=e.length;f<I;f+=3)u=e[f],h=e[f+1],p=e[f+2],A=`${Math.round(u*d)}_${Math.round(h*d)}_${Math.round(p*d)}`,void 0===i[A]&&(i[A]=r.length/3,r.push(u),r.push(h),r.push(p),t&&(l.push(t[f]),l.push(t[f+1]),l.push(t[f+2])),s&&(o.push(s[y]),o.push(s[y+1]))),a[f/3]=i[A],y+=2;for(f=0,I=n.length;f<I;f++)c[f]=a[n[f]];const m={positions:r,indices:c};return l&&(m.normals=l),o&&(m.uv=o),m},buildNormals:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3),i=new r(3),a=new r(3);return(r,l,o)=>{let c,u;const p=new Array(r.length/3);let A,d,f,I,y,m,v;for(c=0,u=l.length;c<u;c+=3){A=l[c],d=l[c+1],f=l[c+2],e[0]=r[3*A],e[1]=r[3*A+1],e[2]=r[3*A+2],t[0]=r[3*d],t[1]=r[3*d+1],t[2]=r[3*d+2],s[0]=r[3*f],s[1]=r[3*f+1],s[2]=r[3*f+2],h.subVec3(t,e,n),h.subVec3(s,e,i);const o=h.vec3();h.normalizeVec3(h.cross3Vec3(n,i,a),o),p[A]||(p[A]=[]),p[d]||(p[d]=[]),p[f]||(p[f]=[]),p[A].push(o),p[d].push(o),p[f].push(o)}for(o=o&&o.length===r.length?o:new Float32Array(r.length),c=0,u=p.length;c<u;c++){I=p[c].length,y=0,m=0,v=0;for(let e=0;e<I;e++)y+=p[c][e][0],m+=p[c][e][1],v+=p[c][e][2];o[3*c]=y/I,o[3*c+1]=m/I,o[3*c+2]=v/I}return o}})(),buildTangents:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3),i=new r(3),a=new r(3),l=new r(3);return(r,o,c)=>{const u=new Float32Array(r.length);for(let p=0;p<o.length;p+=3){let A=o[p];const d=r.subarray(3*A,3*A+3),f=c.subarray(2*A,2*A+2);A=o[p+1];const I=r.subarray(3*A,3*A+3),y=c.subarray(2*A,2*A+2);A=o[p+2];const m=r.subarray(3*A,3*A+3),v=c.subarray(2*A,2*A+2),w=h.subVec3(I,d,e),g=h.subVec3(m,d,t),E=h.subVec2(y,f,s),T=h.subVec2(v,f,n),b=1/(E[0]*T[1]-E[1]*T[0]),D=h.mulVec3Scalar(h.subVec3(h.mulVec3Scalar(w,T[1],i),h.mulVec3Scalar(g,E[1],a),l),b,a);let P;for(let e=0;e<3;e++)P=3*o[p+e],u[P]+=D[0],u[P+1]+=D[1],u[P+2]+=D[2]}return u}})(),buildPickTriangles(e,t,s){const n=t.length,i=s?new Uint16Array(9*n):new Float32Array(9*n),a=new Uint8Array(12*n);let r,l,o,c,u,h,p=0,A=0,d=0;for(let s=0;s<n;s+=3)h=p>>24&255,u=p>>16&255,c=p>>8&255,o=255&p,l=t[s],r=3*l,i[A++]=e[r],i[A++]=e[r+1],i[A++]=e[r+2],a[d++]=o,a[d++]=c,a[d++]=u,a[d++]=h,l=t[s+1],r=3*l,i[A++]=e[r],i[A++]=e[r+1],i[A++]=e[r+2],a[d++]=o,a[d++]=c,a[d++]=u,a[d++]=h,l=t[s+2],r=3*l,i[A++]=e[r],i[A++]=e[r+1],i[A++]=e[r+2],a[d++]=o,a[d++]=c,a[d++]=u,a[d++]=h,p++;return{positions:i,colors:a}},faceToVertexNormals(e,t,s={}){const n=s.smoothNormalsAngleThreshold||20,i={},a=[],r={};let l,o,c,u,p;const A=1e4;let d,f,I,y,m,v;for(f=0,y=e.length;f<y;f+=3){d=f/3,o=e[f],c=e[f+1],u=e[f+2],p=`${Math.round(o*A)}_${Math.round(c*A)}_${Math.round(u*A)}`,void 0===i[p]?i[p]=[d]:i[p].push(d);const s=h.normalizeVec3([t[f],t[f+1],t[f+2]]);a[d]=s,l=h.vec4([s[0],s[1],s[2],1]),r[d]=l}for(p in i)if(i.hasOwnProperty(p)){const e=i[p],t=e.length;for(f=0;f<t;f++){const s=e[f];for(l=r[s],I=0;I<t;I++){if(f===I)continue;const t=e[I];m=a[s],v=a[t];Math.abs(h.angleVec3(m,v)/h.DEGTORAD)<n&&(l[0]+=v[0],l[1]+=v[1],l[2]+=v[2],l[3]+=1)}}}for(f=0,y=t.length;f<y;f+=3)l=r[f/3],t[f+0]=l[0]/l[3],t[f+1]=l[1]/l[3],t[f+2]=l[2]/l[3]},transformRay:(()=>{const e=new r(4),t=new r(4);return(s,n,i,a,r)=>{e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=1,h.transformVec4(s,e,t),a[0]=t[0],a[1]=t[1],a[2]=t[2],e[0]=i[0],e[1]=i[1],e[2]=i[2],h.transformVec3(s,e,t),h.normalizeVec3(t),r[0]=t[0],r[1]=t[1],r[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new r(16),t=new r(16),s=new r(4),n=new r(4),i=new r(4),a=new r(4);return(r,l,o,c,u,p)=>{const A=h.mulMat4(o,l,e),d=h.inverseMat4(A,t),f=r.width,I=r.height,y=(c[0]-f/2)/(f/2),m=-(c[1]-I/2)/(I/2);s[0]=y,s[1]=m,s[2]=-1,s[3]=1,h.transformVec4(d,s,n),h.mulVec4Scalar(n,1/n[3]),i[0]=y,i[1]=m,i[2]=1,i[3]=1,h.transformVec4(d,i,a),h.mulVec4Scalar(a,1/a[3]),u[0]=a[0],u[1]=a[1],u[2]=a[2],h.subVec3(a,n,p),h.normalizeVec3(p)}})(),canvasPosToLocalRay:(()=>{const e=new r(3),t=new r(3);return(s,n,i,a,r,l,o)=>{h.canvasPosToWorldRay(s,n,i,r,e,t),h.worldRayToLocalRay(a,e,t,l,o)}})(),worldRayToLocalRay:(()=>{const e=new r(16),t=new r(4),s=new r(4);return(n,i,a,r,l)=>{const o=h.inverseMat4(n,e);t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,h.transformVec4(o,t,s),r[0]=s[0],r[1]=s[1],r[2]=s[2],h.transformVec3(o,a,l)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,n,i,a){const l=new r(6),o={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:l};let c,u;for(l[0]=l[1]=l[2]=Number.POSITIVE_INFINITY,l[3]=l[4]=l[5]=Number.NEGATIVE_INFINITY,c=0,u=s.length;c<u;++c){var h=3*s[c];for(let e=0;e<3;++e){const t=3*n[h+e];i[t]<l[0]&&(l[0]=i[t]),i[t]>l[3]&&(l[3]=i[t]),i[t+1]<l[1]&&(l[1]=i[t+1]),i[t+1]>l[4]&&(l[4]=i[t+1]),i[t+2]<l[2]&&(l[2]=i[t+2]),i[t+2]>l[5]&&(l[5]=i[t+2])}}if(s.length<20||a>10)return o.triangles=s,o.leaf=!0,o;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];let p=0;e[1]>e[p]&&(p=1),e[2]>e[p]&&(p=2),o.splitDim=p;const A=(l[p]+l[p+3])/2,d=new Array(s.length);let f=0;const I=new Array(s.length);let y=0;for(c=0,u=s.length;c<u;++c){const e=n[h=3*s[c]],t=3*n[h+1],a=3*n[h+2];i[3*e+p]<=A||i[t+p]<=A||i[a+p]<=A?d[f++]=s[c]:I[y++]=s[c]}return d.length=f,I.length=y,o.left=t(d,n,i,a+1),o.right=t(I,n,i,a+1),o}return(e,s)=>{const n=e.length/3,i=new Array(n);for(let e=0;e<n;++e)i[e]=e;return t(i,e,s,0)}})(),decompressPosition(e,t,s){(s=s||e)[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[12],s[n+1]=e[n+1]*t[5]+t[13],s[n+2]=e[n+2]*t[10]+t[14];return s},decompressUV(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[6],s[n+1]=e[n+1]*t[4]+t[7];return s},octDecodeVec2(e,t){let s=e[0],n=e[1];s=(2*s+1)/255,n=(2*n+1)/255;const i=1-Math.abs(s)-Math.abs(n);i<0&&(s=(1-Math.abs(n))*(s>=0?1:-1),n=(1-Math.abs(s))*(n>=0?1:-1));const a=Math.sqrt(s*s+n*n+i*i);return t[0]=s/a,t[1]=n/a,t[2]=i/a,t},octDecodeVec2s(e,t){for(let s=0,n=0,i=e.length;s<i;s+=2){let i=e[s+0],a=e[s+1];i=(2*i+1)/255,a=(2*a+1)/255;const r=1-Math.abs(i)-Math.abs(a);r<0&&(i=(1-Math.abs(a))*(i>=0?1:-1),a=(1-Math.abs(i))*(a>=0?1:-1));const l=Math.sqrt(i*i+a*a+r*r);t[n+0]=i/l,t[n+1]=a/l,t[n+2]=r/l,n+=3}return t}};h.buildEdgeIndices=function(){const e=[],t=[],s=[],n=[],i=[];let a=0;const r=new Uint16Array(3),l=new Uint16Array(3),o=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3();return function(y,m,v,w){!function(i,a){const r={};let l,o,c,u;const h=Math.pow(10,4);let p,A,d=0;for(p=0,A=i.length;p<A;p+=3)l=i[p],o=i[p+1],c=i[p+2],u=Math.round(l*h)+"_"+Math.round(o*h)+"_"+Math.round(c*h),void 0===r[u]&&(r[u]=d/3,e[d++]=l,e[d++]=o,e[d++]=c),t[p/3]=r[u];for(p=0,A=a.length;p<A;p++)n[p]=t[a[p]],s[n[p]]=a[p]}(y,m),function(t,s){a=0;for(let y=0,m=t;y<m;y+=3){const t=3*n[y],m=3*n[y+1],v=3*n[y+2];s?(r[0]=e[t],r[1]=e[t+1],r[2]=e[t+2],l[0]=e[m],l[1]=e[m+1],l[2]=e[m+2],o[0]=e[v],o[1]=e[v+1],o[2]=e[v+2],h.decompressPosition(r,s,c),h.decompressPosition(l,s,u),h.decompressPosition(o,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[m],u[1]=e[m+1],u[2]=e[m+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,A),h.subVec3(c,u,d),h.cross3Vec3(A,d,f),h.normalizeVec3(f,I);const w=i[a]||(i[a]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],a++}}(m.length,v);const g=[],E=Math.cos(h.DEGTORAD*w),T={};let b,D,P,R,C,_,B,O,S,N,x,L=!1;for(let e=0,t=m.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=n[e+s],D=n[e+(s+1)%3],P=Math.min(b,D),R=Math.max(b,D),C=P+","+R,void 0===T[C]?T[C]={index1:P,index2:R,face1:t,face2:void 0}:T[C].face2=t}for(C in T)_=T[C],void 0!==_.face2&&(B=i[_.face1].normal,O=i[_.face2].normal,S=h.dotVec3(B,O),S>E)||(N=s[_.index1],x=s[_.index2],(!L&&N>65535||x>65535)&&(L=!0),g.push(N),g.push(x));return L?new Uint32Array(g):new Uint16Array(g)}}(),h.planeClipsPositions3=function(e,t,s,n=3){for(let i=0,a=s.length;i<a;i+=n){if(l[0]=s[i+0]-e[0],l[1]=s[i+1]-e[1],l[2]=s[i+2]-e[2],l[0]*t[0]+l[1]*t[1]+l[2]*t[2]<0)return!0}return!1};const p=new Float32Array(3);class A{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),n=s+e[1],i=s;i<n;++i)t.push(i);return String.fromCharCode.apply(null,t)})).join("");function I(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return f.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const y=function(){for(var e={},t=window.location.search.substring(1).split("&"),s=0;s<t.length;s++){var n=t[s].split("=");if(void 0===e[n[0]])e[n[0]]=decodeURIComponent(n[1]);else if("string"==typeof e[n[0]]){var i=[e[n[0]],decodeURIComponent(n[1])];e[n[0]]=i}else e[n[0]].push(decodeURIComponent(n[1]))}return e}();const m={xmlToJson:function e(t,s){if(t.nodeType===t.TEXT_NODE){var n=t.nodeValue;if(null===n.match(/^\s+$/))return n}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var i={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var a=0;a<t.attributes.length;a++){var r=t.attributes[a];i[s[r.nodeName]||r.nodeName]=r.nodeValue}for(var l=0;l<t.childNodes.length;l++){(a=e(t.childNodes[l],s))&&i.children.push(a)}return i}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return I(t[0],2)+[1,4,7,10,13].map((function(e){return I((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var s=[],n=function(e){e.type===t&&s.push(e),(e.children||[]).forEach((function(e){n(e)}))};return n(e),s},timeout:function(e){return new Promise((function(t,s){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,s){var n=new XMLHttpRequest;n.open(e.method||"GET",e.url,!0),n.onload=function(e){4===n.readyState&&(200===n.status?t(n.responseXML):s(n.statusText))},n.send(null)}))},loadJSON:function(e,t,s){var n=e=>{};t=t||n,s=s||n;var i=new XMLHttpRequest;i.overrideMimeType("application/json"),i.open("GET",e,!0),i.addEventListener("load",(function(e){var n=e.target.response;if(200===this.status){var i;try{i=JSON.parse(n)}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(i)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(n))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),i.addEventListener("error",(function(e){s(e)}),!1),i.send(null)},loadArraybuffer:function(e,t,s){var n=e=>{};t=t||n,s=s||n;const i=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(i){const e=!!i[2];var a=i[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),s=new Uint8Array(e);for(var r=0;r<a.length;r++)s[r]=a.charCodeAt(r);window.setTimeout((function(){t(e)}),0)}catch(e){window.setTimeout((function(){s(e)}),0)}}else{const n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onreadystatechange=function(){4===n.readyState&&(200===n.status?t(n.response):s("loadArrayBuffer error : "+n.response))},n.send(null)}},queryString:y,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return m.isString(e)||m.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(m.isNumeric(e)||m.isString(e)?`${e}`:e.id)===(m.isNumeric(t)||m.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return m.apply(e,{})},apply:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(t[s]=e[s]);return t},apply2:function(e,t){for(const s in e)e.hasOwnProperty(s)&&void 0!==e[s]&&null!==e[s]&&(t[s]=e[s]);return t},applyIf:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(void 0!==t[s]&&null!==t[s]||(t[s]=e[s]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return m.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const s=new e.constructor(e.length+t.length);return s.set(e),s.set(t,e.length),s},flattenParentChildHierarchy:function(e){var t=[];return function e(s){s.id=s.uuid,delete s.oid,t.push(s);var n=s.children;if(n)for(var i=0,a=n.length;i<a;i++){n[i].parent=s.id,e(n[i])}s.children=[]}(e),t}},v={},w=new e,g=new A,E={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let b,D=0,P=0;const R=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(R.scenes[e.id])return void console.error(`[ERROR] Scene ${m.inQuotes(e.id)} already exists`)}else e.id=w.addItem({});R.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;v[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{w.removeItem(e.id),delete R.scenes[e.id],delete v[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in R.scenes)R.scenes.hasOwnProperty(t)&&(e=R.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete R.scenes[e.id]))},this.scheduleTask=function(e,t){g.push(e),g.push(t)},this.runTasks=function(e=-1){let t,s,n=(new Date).getTime(),i=0;for(;g.length>0&&(e<0||n<e);)t=g.shift(),s=g.shift(),s?t.call(s):t(),n=(new Date).getTime(),i++;return i},this.getNumTasks=function(){return g.length}},C=function(){let e=Date.now();if(b=e-D,D>0&&b>0){var t=1e3/b;P+=t,T.push(t),T.length>=30&&(P-=T.shift()),d.frame.fps=Math.round(P/T.length)}!function(e){const t=R.runTasks(e+10),s=R.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in E.time=e,R.scenes)if(R.scenes.hasOwnProperty(t)){var s=R.scenes[t];E.sceneId=t,E.startTime=s.startTime,E.deltaTime=null!=E.prevTime?E.time-E.prevTime:0,s.fire("tick",E,!0)}E.prevTime=e}(e),function(){const e=R.scenes,t=!1;let s,n,i,a,r;for(r in e)e.hasOwnProperty(r)&&(s=e[r],n=v[r],n||(n=v[r]={}),i=s.ticksPerOcclusionTest,n.ticksPerOcclusionTest!==i&&(n.ticksPerOcclusionTest=i,n.renderCountdown=i),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=i),a=s.ticksPerRender,n.ticksPerRender!==a&&(n.ticksPerRender=a,n.renderCountdown=a),0==--n.renderCountdown&&(s.render(t),n.renderCountdown=a))}(),D=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C);class _{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof _))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];let i;if(n)for(const s in n)n.hasOwnProperty(s)&&(i=n[s],this._eventCallDepth++,this._eventCallDepth<300?i.callback.call(i.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let i=this._eventSubs[t];i?this._eventSubsNum[t]++:(i={},this._eventSubs[t]=i,this._eventSubsNum[t]=1);const a=this._subIdMap.addItem();i[a]={callback:s,scope:n||this},this._subIdEvents[a]=t;const r=this._events[t];return void 0!==r&&s.call(n||this,r),a}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const n=this,i=this.on(e,(function(e){n.off(i),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+m.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let s=e.component;const n=e.sceneDefault,i=e.sceneSingleton,a=e.type,r=e.on,l=!1!==e.recompiles;if(s&&(m.isNumeric(s)||m.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+m.inQuotes(e))}if(!s)if(!0===i){const e=this.scene.types[a];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===n&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+m.inQuotes(s.id));if(a&&!s.isType(a))return void this.error("Expected a "+a+" type or subtype: "+s.type+" "+m.inQuotes(s.id))}this._attachments||(this._attachments={});const o=this._attached[t];let c,u,h;if(o){if(s&&o.id===s.id)return;const e=this._attachments[o.id];for(c=e.subs,u=0,h=c.length;u<h;u++)o.off(c[u]);delete this._attached[t],delete this._attachments[o.id];const n=e.params.onDetached;n&&(m.isFunction(n)?n(o):n.scope?n.callback.call(n.scope,o):n.callback(o)),e.managingLifecycle&&o.destroy()}if(s){const n={params:e,component:s,subs:[],managingLifecycle:false};n.subs.push(s.once("destroyed",(function(){n.params.component=null,this._attach(n.params)}),this)),l&&n.subs.push(s.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=s,this._attachments[s.id]=n;const i=e.onAttached;if(i&&(m.isFunction(i)?i(s):i.scope?i.callback.call(i.scope,s):i.callback(s)),r){let e,t,i,a;for(e in r)if(r.hasOwnProperty(e)){if(t=r[e],m.isFunction(t)?(i=t,a=null):(i=t.callback,a=t.scope),!i)continue;n.subs.push(s.on(e,i,a))}}}return l&&this.fire("dirty",this),this.fire(t,s),s}_checkComponent(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var s=0,n=e.length;s<n;s++)if(e[s]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():R.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,n,i,a;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],s=t.component,n=t.subs,i=0,a=n.length;i<a;i++)s.off(n[i]);t.managingLifecycle&&s.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(s=this._ownedComponents[e],s.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const B=h.vec3(),O=h.vec3(),S=h.mat4();class N{constructor(){this.normal=h.vec3(),this.offset=0,this.testVertex=h.vec3()}set(e,t,s,n){const i=1/Math.sqrt(e*e+t*t+s*s);this.normal[0]=e*i,this.normal[1]=t*i,this.normal[2]=s*i,this.offset=n*i,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class x{constructor(){this.planes=[new N,new N,new N,new N,new N,new N]}}function L(e,t,s){const n=h.mulMat4(s,t,S),i=n[0],a=n[1],r=n[2],l=n[3],o=n[4],c=n[5],u=n[6],p=n[7],A=n[8],d=n[9],f=n[10],I=n[11],y=n[12],m=n[13],v=n[14],w=n[15];e.planes[0].set(l-i,p-o,I-A,w-y),e.planes[1].set(l+i,p+o,I+A,w+y),e.planes[2].set(l-a,p-c,I-d,w-m),e.planes[3].set(l+a,p+c,I+d,w+m),e.planes[4].set(l-r,p-u,I-f,w-v),e.planes[5].set(l+r,p+u,I+f,w+v)}function M(e,t){let s=x.INSIDE;const n=B,i=O;n[0]=t[0],n[1]=t[1],n[2]=t[2],i[0]=t[3],i[1]=t[4],i[2]=t[5];const a=[n,i];for(let t=0;t<6;++t){const n=e.planes[t];if(n.normal[0]*a[n.testVertex[0]][0]+n.normal[1]*a[n.testVertex[1]][1]+n.normal[2]*a[n.testVertex[2]][2]+n.offset<0)return x.OUTSIDE;n.normal[0]*a[1-n.testVertex[0]][0]+n.normal[1]*a[1-n.testVertex[1]][1]+n.normal[2]*a[1-n.testVertex[2]][2]+n.offset<0&&(s=x.INTERSECT)}return s}x.INSIDE=0,x.INTERSECT=1,x.OUTSIDE=2;class F extends _{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=h.vec2(),this._canvasMarqueeCorner2=h.vec2(),this._canvasMarquee=h.AABB2(),this._marqueeFrustum=new x,this._marqueeFrustumProjMat=h.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==F.PICK_MODE_INSIDE&&e!==F.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===F.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(s,n=x.INTERSECT)=>{if(n===x.INTERSECT&&(n=M(this._marqueeFrustum,s.aabb)),n!==x.OUTSIDE){if(s.entities){const t=s.entities;for(let s=0,n=t.length;s<n;s++){const n=t[s];if(!n.visible)continue;const i=n.aabb;if(this._pickMode===F.PICK_MODE_INSIDE){M(this._marqueeFrustum,i)===x.INSIDE&&e.push(n.id)}else{M(this._marqueeFrustum,i)!==x.OUTSIDE&&e.push(n.id)}}}s.left&&t(s.left,n),s.right&&t(s.right,n)}};return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,s=e.clientHeight,n=e.clientLeft,i=e.clientTop,a=2/t,r=2/s,l=e.clientHeight/e.clientWidth,o=(this._canvasMarquee[0]-n)*a-1,c=(this._canvasMarquee[2]-n)*a-1,u=-(this._canvasMarquee[3]-i)*r+1,p=-(this._canvasMarquee[1]-i)*r+1,A=this.viewer.scene.camera.frustum.near*(17*l);h.frustumMat4(o,c,u*l,p*l,A,1e4,this._marqueeFrustumProjMat),L(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}F.PICK_MODE_INTERSECTS=0,F.PICK_MODE_INSIDE=1;class H{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];let i;if(n)for(const s in n)n.hasOwnProperty(s)&&(i=n[s],this._eventCallDepth++,this._eventCallDepth<300?i.callback.call(i.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let i=this._eventSubs[t];i?this._eventSubsNum[t]++:(i={},this._eventSubs[t]=i,this._eventSubsNum[t]=1);const a=this._subIdMap.addItem();i[a]={callback:s,scope:n||this},this._subIdEvents[a]=t;const r=this._events[t];return void 0!==r&&s.call(n||this,r),a}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const n=this,i=this.on(e,(function(e){n.off(i),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const U=h.vec3(),G=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(n,i,a){return a=a||e,t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,h.transformVec4(n,t,s),h.setMat4Translation(n,s,a),a.slice()}}();function j(e,t,s){const n=Float32Array.from([e[0]])[0],i=e[0]-n,a=Float32Array.from([e[1]])[0],r=e[1]-a,l=Float32Array.from([e[2]])[0],o=e[2]-l;t[0]=n,t[1]=a,t[2]=l,s[0]=i,s[1]=r,s[2]=o}function V(e,t,s,n=1e3){const i=h.getPositionsCenter(e,U),a=Math.round(i[0]/n)*n,r=Math.round(i[1]/n)*n,l=Math.round(i[2]/n)*n;s[0]=a,s[1]=r,s[2]=l;const o=0!==s[0]||0!==s[1]||0!==s[2];if(o)for(let s=0,n=e.length;s<n;s+=3)t[s+0]=e[s+0]-a,t[s+1]=e[s+1]-r,t[s+2]=e[s+2]-l;return o}function k(e,t,s,n){const i=h.dotVec3(t,s)+e,a=h.normalizeVec3(t,U);return h.mulVec3Scalar(a,-i,n),n}const Q=1,W=4,z=8,K=16,Y=32,X=256,q=512,J=1024,Z=2048,$=new Float32Array([0,0,0]),ee=new Uint16Array([0,0,0]);h.OBB3();class te{constructor(e,t,s,n,i,a,r){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=n,this._numPrimitives=0;for(let e=0,t=this.meshes.length;e<t;e++){const t=this.meshes[e];t.parent=this,t.entity=this,this._numPrimitives+=t.numPrimitives}this.id=s,this.originalSystemId=h.unglobalizeObjectId(e.id,s),this._flags=i,this._aabb=a,this._worldAABB=h.AABB3(a),this._offsetAABB=h.AABB3(a),this._aabbDirty=!0,this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!r,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}_transformDirty(){this._aabbDirty=!0,this.model._transformDirty()}_sceneModelDirty(){this._aabbDirty=!0;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._sceneModelDirty()}get aabb(){if(this._aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this.meshes.length;e<t;e++)h.expandAABB3(this._aabb,this.meshes[e].aabb);this._aabbDirty=!1}return this._aabb}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get numPrimitives(){return this._numPrimitives}get numTriangles(){return this._numPrimitives}get visible(){return this._getFlag(Q)}set visible(e){if(!!(this._flags&Q)!==e){this._flags=e?this._flags|Q:this._flags&~Q;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}get highlighted(){return this._getFlag(q)}set highlighted(e){if(!!(this._flags&q)!==e){this._flags=e?this._flags|q:this._flags&~q;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(X)}set xrayed(e){if(!!(this._flags&X)!==e){this._flags=e?this._flags|X:this._flags&~X;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}get selected(){return this._getFlag(J)}set selected(e){if(!!(this._flags&J)!==e){this._flags=e?this._flags|J:this._flags&~J;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}get edges(){return this._getFlag(Z)}set edges(e){if(!!(this._flags&Z)!==e){this._flags=e?this._flags|Z:this._flags&~Z;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this._setCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this._setCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this._setCulled()}_setCulled(){let e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&W)!==e){this._flags=e?this._flags|W:this._flags&~W;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(K)}set clippable(e){if(!!(this._flags&K)!==e){this._flags=e?this._flags|K:this._flags&~K;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(Y)}set collidable(e){if(!!(this._flags&Y)!==e){this._flags=e?this._flags|Y:this._flags&~Y;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(z)}set pickable(e){if(!!(this._flags&z)!==e){this._flags=e?this._flags|z:this._flags&~z;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return $[0]=e[0]/255,$[1]=e[1]/255,$[2]=e[2]/255,$}set colorize(e){if(e){ee[0]=Math.floor(255*e[0]),ee[1]=Math.floor(255*e[1]),ee[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(ee)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let n=255;if(t){if(e<0?e=0:e>1&&(e=1),n=Math.floor(255*e),s===n)return}else if(n=255,s===n)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(n,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._aabbDirty=!0,this.model._aabbDirty=!0,this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model.glRedraw()}get saoEnabled(){return this.model.saoEnabled}getEachVertex(e){for(let t=0,s=this.meshes.length;t<s;t++)this.meshes[t].getEachVertex(e)}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this._opacityUpdated&&this.scene._objectColorizeUpdated(this,!1),this._opacityUpdated&&this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const se=h.vec4(),ne=h.vec4();class ie extends _{constructor(e,t){super(e,t),this._entity=null,this._visible=null,this._worldPos=h.vec3(),this._origin=h.vec3(),this._rtcPos=h.vec3(),this._viewPos=h.vec3(),this._canvasPos=h.vec2(),this._occludable=!1,this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(h.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){se.set(this._viewPos),se[3]=1,h.transformPoint4(this.scene.camera.projMatrix,se,ne);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ne[0]/ne[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ne[1]/ne[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof te?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),j(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class ae{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,n=s.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var i=this._wireClickable,a=i.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=0,a["pointer-events"]="none",t.onContextMenu,e.appendChild(i),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var n=this._wireClickable.style;n.width=Math.round(e)+"px",n.left=Math.round(this._x1)+"px",n.top=Math.round(this._y1)+"px",n["-webkit-transform"]="rotate("+t+"deg)",n["-moz-transform"]="rotate("+t+"deg)",n["-ms-transform"]="rotate("+t+"deg)",n["-o-transform"]="rotate("+t+"deg)",n.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,n){this._x1=e,this._y1=t,this._x2=s,this._y2=n,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class re{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!0,this._culled=!1;var s=this._dot,n=s.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==t.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var i=this._dotClickable,a=i.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",t.onContextMenu,e.appendChild(i),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var n=this._dotClickable.style;n.left=Math.round(e)-9+"px",n.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class le{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,n=s.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,n){var i=e+.5*(s-e),a=t+.5*(n-t),r=this._label.style;r.left=Math.round(i)-20+"px",r.top=Math.round(a)-12+"px"}setPosBetweenWires(e,t,s,n,i,a){var r=(e+s+i)/3,l=(t+n+a)/3,o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(l)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var oe=h.vec3(),ce=h.vec3();class ue extends _{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._cornerMarker=new ie(s,t.corner),this._targetMarker=new ie(s,t.target),this._originWorld=h.vec3(),this._cornerWorld=h.vec3(),this._targetWorld=h.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._cornerDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._originWire=new ae(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetWire=new ae(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._angleLabel=new le(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const A=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],I=this._targetMarker.viewPos[2];if(d>A||f>A||I>A)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,n=e.canvas.canvas.getBoundingClientRect();const y=this._container.getBoundingClientRect();for(var i=n.top-y.top,a=n.left-y.left,r=e.canvas.boundary,l=r[2],o=r[3],c=0,u=0,p=t.length;u<p;u+=4)s[c]=a+Math.floor((1+t[u+0]/t[u+3])*l/2),s[c+1]=i+Math.floor((1-t[u+1]/t[u+3])*o/2),c+=2;if(this._originDot.setPos(s[0],s[1]),this._cornerDot.setPos(s[2],s[3]),this._targetDot.setPos(s[4],s[5]),this._originWire.setStartAndEnd(s[0],s[1],s[2],s[3]),this._targetWire.setStartAndEnd(s[2],s[3],s[4],s[5]),this._angleLabel.setPosBetweenWires(s[0],s[1],s[2],s[3],s[4],s[5]),h.subVec3(this._originWorld,this._cornerWorld,oe),h.subVec3(this._targetWorld,this._cornerWorld,ce),!(0===oe[0]&&0===oe[1]&&0===oe[2]||0===ce[0]&&0===ce[1]&&0===ce[2])){const e=this._approximate?" ~ ":" = ";h.normalizeVec3(oe),h.normalizeVec3(ce);const t=Math.abs(h.angleVec3(oe,ce));this._angle=t/h.DEGTORAD,this._angleLabel.setText(e+this._angle.toFixed(2)+"°")}else this._angleLabel.setText("");this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setCulled(!(this._visible&&this._angleVisible&&this.labelsVisible)),this._cpDirty=!1}}_isSliced(e){const t=this.scene._sectionPlanesState.sectionPlanes;for(let s=0,n=t.length;s<n;s++){const n=t[s];if(h.planeClipsPositions3(n.pos,n.dir,e,4))return!0}return!1}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get corner(){return this._cornerMarker}get target(){return this._targetMarker}get angle(){return this._update(),this._angle}get color(){return this._color}set color(e){this._originDot.setFillColor(e),this._cornerDot.setFillColor(e),this._targetDot.setFillColor(e),this._originWire.setColor(e||"blue"),this._targetWire.setColor(e||"red"),this._angleLabel.setFillColor(e||"#00BBFF"),this._color=e}set visible(e){e=!1!==e,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=!1!==e,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cpDirty=!0,this._needUpdate()}get originVisible(){return this._originVisible}set cornerVisible(e){e=!1!==e,this._cornerVisible=e,this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._cpDirty=!0,this._needUpdate()}get cornerVisible(){return this._cornerVisible}set targetVisible(e){e=!1!==e,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible),this._cpDirty=!0,this._needUpdate()}get targetVisible(){return this._targetVisible}set originWireVisible(e){e=!1!==e,this._originWireVisible=e,this._originWire.setVisible(this._visible&&this._originWireVisible),this._cpDirty=!0,this._needUpdate()}get originWireVisible(){return this._originWireVisible}set targetWireVisible(e){e=!1!==e,this._targetWireVisible=e,this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._cpDirty=!0,this._needUpdate()}get targetWireVisible(){return this._targetWireVisible}set angleVisible(e){e=!1!==e,this._angleVisible=e,this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get angleVisible(){return this._angleVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._angleLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._cornerDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._originWire.setHighlighted(e),this._targetWire.setHighlighted(e),this._angleLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._cornerDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._originWire.setClickable(this._clickable),this._targetWire.setClickable(this._clickable),this._angleLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onSectionPlaneUpdated&&e.off(this._onSectionPlaneUpdated),this._originDot.destroy(),this._cornerDot.destroy(),this._targetDot.destroy(),this._originWire.destroy(),this._targetWire.destroy(),this._angleLabel.destroy(),super.destroy()}}class he extends _{get active(){}set snapping(e){}get snapping(){return!0}activate(){}deactivate(){}reset(){}destroy(){}}class pe extends he{constructor(e,t={}){super(e.viewer.scene),this.pointerLens=t.pointerLens,this._active=!1,this._mouseState=0,this._currentAngleMeasurement=null;const s=document.createElement("div"),n=this.scene.canvas.canvas;n.parentNode.insertBefore(s,n),s.style.background="black",s.style.border="2px solid blue",s.style.borderRadius="10px",s.style.width="5px",s.style.height="5px",s.style.margin="-200px -200px",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",this.markerDiv=s,this._onMouseHoverSurface=null,this._onHoverNothing=null,this._onPickedNothing=null,this._onPickedSurface=null,this._onInputMouseDown=null,this._onInputMouseUp=null,this._snapping=!1!==t.snapping,this._attachPlugin(e,t)}_attachPlugin(e,t={}){this.angleMeasurementsPlugin=e,this.plugin=e}get active(){return this._active}set snapping(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}get snapping(){return this._snapping}activate(){if(this._active)return;this.angleMeasurementsPlugin;const e=this.scene;e.input;const t=e.canvas.canvas,s=this.angleMeasurementsPlugin.viewer.cameraControl,n=this.pointerLens;let i=!1,a=!1,r=0,l=0;const o=h.vec3(),c=h.vec2();this._currentAngleMeasurement=null,this._onMouseHoverSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(n&&(n.visible=!0,n.canvasPos=e.canvasPos,n.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,n.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(n&&(n.visible=!0,n.canvasPos=e.canvasPos,n.snappedCanvasPos=e.canvasPos,n.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const s=e.snappedCanvasPos||e.canvasPos;switch(i=!0,a=e.entity,o.set(e.worldPos),c.set(s),this._mouseState){case 0:this.markerDiv.style.marginLeft=s[0]-5+"px",this.markerDiv.style.marginTop=s[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(r=e.clientX,l=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>r+20||e.clientX<r-20||e.clientY>l+20||e.clientY<l-20))switch(this._mouseState){case 0:i&&(this._currentAngleMeasurement=this.angleMeasurementsPlugin.createMeasurement({id:h.createUUID(),origin:{entity:a,worldPos:o},corner:{entity:a,worldPos:o},target:{entity:a,worldPos:o},approximate:!0}),this._currentAngleMeasurement.clickable=!1,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.angleVisible=!1,this._mouseState=1,this.angleMeasurementsPlugin.fire("measurementStart",this._currentAngleMeasurement));break;case 1:i?(this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._mouseState=2):this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._mouseState=0,this.angleMeasurementsPlugin.fire("measurementCancel",this._currentAngleMeasurement));break;case 2:i?(this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.clickable=!0,this.angleMeasurementsPlugin.fire("measurementEnd",this._currentAngleMeasurement),this._currentAngleMeasurement=null,this._mouseState=0):this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._mouseState=0,this.angleMeasurementsPlugin.fire("measurementCancel",this._currentAngleMeasurement))}}),this._onMouseHoverOff=s.on(this._snapping?"hoverSnapOrSurfaceOff":"hoverOff",(e=>{if(i=!1,n&&(n.visible=!0,n.pointerPos=e.canvasPos,n.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,n.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class Ae extends ie{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],s=e[1],n=this.canvasPos;this._marker.style.left=Math.floor(t+n[0])-12+"px",this._marker.style.top=Math.floor(s+n[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+n[0]+20)+"px",this._label.style.top=Math.floor(s+n[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const s=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),s)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const s=e[t];this.setField(t,s)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):this._marker.parentNode.removeChild(this._marker)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const de=h.vec3(),fe=h.vec3(),Ie=h.vec3();class ye extends _{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const me=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class ve extends _{constructor(e,t={}){super(e,t),this._backgroundColor=h.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let n=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(n=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{n&&(n=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new ye(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+h.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),n=s.style;n.height="100%",n.width="100%",n.padding="0",n.margin="0",n.background="rgba(0,0,0,0);",n.float="left",n.left="0",n.top="0",n.position="absolute",n.opacity="1.0",n["z-index"]="-10000",s.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<me.length;e++)try{this.gl=this.canvas.getContext(me[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));{const e=this.gl;let t="__",s=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,s.call(this,e))};let n={},i=e.bindTexture;e.bindTexture=function(e,s){n[t]!==s&&(n[t]=s,i.call(this,e,s))}}this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,s,n){return this.scene._renderer.readPixels(e,t,s,n)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class we{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=h.vec3(),this.snapPickOrigin=h.vec3()}getRTCViewMatrix(e,t){let s=this._rtcViewMats[e];return s||(s=this._getNewMat(),G(this._scene.camera.viewMatrix,t,s),this._rtcViewMats[e]=s),s}getRTCPickViewMatrix(e,t){let s=this._rtcPickViewMats[e];if(!s){s=this._getNewMat();const n=this.pickViewMatrix||this._scene.camera.viewMatrix;G(n,t,s),this._rtcPickViewMats[e]=s}return s}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=h.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}const ge={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},Ee=document.createElement("canvas");if(Ee){const e=Ee.getContext("webgl",{antialias:!0})||Ee.getContext("experimental-webgl",{antialias:!0});ge.WEBGL=!!e,ge.WEBGL&&(ge.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?ge.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?ge.FS_MAX_FLOAT_PRECISION="mediump":ge.FS_MAX_FLOAT_PRECISION="lowp":ge.FS_MAX_FLOAT_PRECISION="mediump",ge.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),ge.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),ge.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),ge.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),ge.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ge.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),ge.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),ge.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),ge.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),ge.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){ge.SUPPORTED_EXTENSIONS[e]=!0})))}class Te{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class be{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),n=[];for(let e=0;e<t.length;e++)n.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(n.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class De{constructor(e,t){this.bindTexture=function(s,n){return!!s.bind(n)&&(e.uniform1i(t,n),!0)}}}class Pe{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const Re=new e({});function Ce(e){const t=[];let s,n;for(let i=0,a=e.length;i<a;i++)s=e[i],n=s.indexOf("/"),n>0&&"/"===s.charAt(n+1)&&(s=s.substring(0,n)),t.push(s);return t.join("\n")}function _e(e){console.error(e.join("\n"))}class Be{constructor(e,t){this.id=Re.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new be(e,e.VERTEX_SHADER,Ce(this.source.vertex)),this._fragmentShader=new be(e,e.FRAGMENT_SHADER,Ce(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void _e(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void _e(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void _e(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void _e(this.errors);let t,s,n,i,a;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void _e(this.errors);const r=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;s<r;++s)n=e.getActiveUniform(this.handle,s),n&&(i=n.name,"\0"===i[i.length-1]&&(i=i.substr(0,i.length-1)),a=e.getUniformLocation(this.handle,i),n.type===e.SAMPLER_2D||n.type===e.SAMPLER_CUBE||35682===n.type||e instanceof WebGL2RenderingContext&&(n.type===e.UNSIGNED_INT_SAMPLER_2D||n.type===e.INT_SAMPLER_2D)?this.samplers[i]=new De(e,a):this.uniforms[i]=a);const l=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(s=0;s<l;s++)t=e.getActiveAttrib(this.handle,s),t&&(a=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new Pe(e,a));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,s){if(!this.allocated)return!1;const n=this.samplers[e];return!!n&&n.bindTexture(t,s)}destroy(){this.allocated&&(Re.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}class Oe{constructor(e,t,s,n,i,a,r,l,o){switch(this._gl=e,this.type=t,this.allocated=!1,s.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=a,this.length=0,this.dataLength=n,this.numItems=0,this.itemSize=i,this.normalized=!!r,this.stride=l||0,this.offset=o||0,this._allocate(s)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Se{constructor(e,t){this.scene=e,this.aabb=h.AABB3(),this.origin=h.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const s=this.markerList[t].worldPos;this.positions[e++]=s[0],this.positions[e++]=s[1],this.positions[e++]=s[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;h.collapseAABB3(e),h.expandAABB3Points3(e,this.positions);const t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,s=this.numMarkers;this.positionsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),s,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,s=e.boundary,n=s[2],i=s[3];let a=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const s=this.markerList[e];if(s.viewPos[2]>-t){s._setVisible(!1);continue}const r=s.canvasPos,l=r[0],o=r[1];l+10<0||o+10<0||l-10>n||o-10>i?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[a++]=l,this.pixels[a++]=o):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s];if(t.active){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const n=0===e;this.sectionPlanesActive[s]=n}else this.sectionPlanesActive[s]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const Ne=h.vec3([1,0,0]),xe=h.vec3();class Le{constructor(e,t){this._scene=e,this._renderBufferManager=t,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new Se(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let n=this._occlusionLayers[s];n||(n=new Se(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),n.addMarker(e),this._markersToOcclusionLayersMap[e.id]=n}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// OcclusionTester fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),n.push("}"),n}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new Be(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,s=this._program,n=e._sectionPlanesState,i=e.camera,a=e.camera.project;if(s.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,s=this._occlusionLayersList.length;e<s;e++){const s=this._occlusionLayersList[e];if(s.update(),s.culledBySectionPlanes)continue;const a=s.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,G(i.viewMatrix,a));const r=n.sectionPlanes.length;if(r>0){const e=n.sectionPlanes;for(let n=0;n<r;n++){const i=this._uSectionPlanes[n];if(i){const r=s.sectionPlanesActive[n];if(t.uniform1i(i.active,r?1:0),r){const s=e[n];t.uniform3fv(i.pos,k(s.dist,s.dir,a,xe)),t.uniform3fv(i.dir,s.dir)}}}}this._aPosition.bindArrayBuffer(s.positionsBuf);const l=s.indicesBuf;l.bind(),t.drawElements(t.POINTS,l.numItems,l.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*Ne[0],s=255*Ne[1],n=255*Ne[2];for(let i=0,a=this._occlusionLayersList.length;i<a;i++){const a=this._occlusionLayersList[i];for(let i=0;i<a.lenOcclusionTestList;i++){const r=a.occlusionTestList[i],l=2*i,o=this._readPixelBuf.read(Math.round(a.pixels[l]*e),Math.round(a.pixels[l+1]*e)),c=o[0]===t&&o[1]===s&&o[2]===n;r._setVisible(c)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const Me=h.vec2();class Fe{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(n.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,n=this._scene,i=n.sao,a=t.drawingBufferWidth,r=t.drawingBufferHeight,l=n.camera.project._state,o=l.near,c=l.far,u=l.matrix,p=this._getInverseProjectMat(),A=Math.random(),d="perspective"===n.camera.projection;Me[0]=a,Me[1]=r,t.viewport(0,0,a,r),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),s.bind(),t.uniform1f(this._uCameraNear,o),t.uniform1f(this._uCameraFar,c),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,u),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,i.scale*(c/5)),t.uniform1f(this._uIntensity,i.intensity),t.uniform1f(this._uBias,i.bias),t.uniform1f(this._uKernelRadius,i.kernelRadius),t.uniform1f(this._uMinResolution,i.minResolution),t.uniform2fv(this._uViewport,Me),t.uniform1f(this._uRandomSeed,A);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Be(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const n=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),a=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(s,s.ARRAY_BUFFER,i,i.length,3,s.STATIC_DRAW),this._uvBuf=new Oe(s,s.ARRAY_BUFFER,n,n.length,2,s.STATIC_DRAW),this._indicesBuf=new Oe(s,s.ELEMENT_ARRAY_BUFFER,a,a.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const He=new Float32Array(Qe(17,[0,1])),Ue=new Float32Array(Qe(17,[1,0])),Ge=new Float32Array(function(e,t){const s=[];for(let n=0;n<=e;n++)s.push(ke(n,t));return s}(17,4)),je=new Float32Array(2);class Ve{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Be(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new Oe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,n,n.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(a.camera.projMatrix,t),t)})());const n=this._scene.canvas.gl,i=this._program,a=this._scene,r=n.drawingBufferWidth,l=n.drawingBufferHeight,o=a.camera.project._state,c=o.near,u=o.far;n.viewport(0,0,r,l),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),i.bind(),je[0]=r,je[1]=l,n.uniform2fv(this._uViewport,je),n.uniform1f(this._uCameraNear,c),n.uniform1f(this._uCameraFar,u),n.uniform1f(this._uDepthCutoff,.01),0===s?n.uniform2fv(this._uSampleOffsets,Ue):n.uniform2fv(this._uSampleOffsets,He),n.uniform1fv(this._uSampleWeights,Ge);const p=e.getDepthTexture(),A=t.getTexture();i.bindTexture(this._uDepthTexture,p,0),i.bindTexture(this._uOcclusionTexture,A,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),n.drawElements(n.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function ke(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Qe(e,t){const s=[];for(let n=0;n<=e;n++)s.push(t[0]*n),s.push(t[1]*n);return s}class We{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,s=null){const n=this.gl,i=n.createTexture();return n.bindTexture(n.TEXTURE_2D,i),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),s?n.texStorage2D(n.TEXTURE_2D,1,s,e,t):n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null),i}_touch(...e){let t,s;const n=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=n.drawingBufferWidth,s=n.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;this.buffer.textures.forEach((e=>n.deleteTexture(e))),n.deleteFramebuffer(this.buffer.framebuf),n.deleteRenderbuffer(this.buffer.renderbuf)}const i=[];let a;e.length>0?i.push(...e.map((e=>this.createTexture(t,s,e)))):i.push(this.createTexture(t,s)),this._hasDepthTexture&&(a=n.createTexture(),n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.DEPTH_COMPONENT32F,t,s,0,n.DEPTH_COMPONENT,n.FLOAT,null));const r=n.createRenderbuffer();n.bindRenderbuffer(n.RENDERBUFFER,r),n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_COMPONENT32F,t,s);const l=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,l);for(let e=0;e<i.length;e++)n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+e,n.TEXTURE_2D,i[e],0);if(e.length>0&&n.drawBuffers(i.map(((e,t)=>n.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?n.framebufferTexture2D(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.TEXTURE_2D,a,0):n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,r),n.bindTexture(n.TEXTURE_2D,null),n.bindRenderbuffer(n.RENDERBUFFER,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindFramebuffer(n.FRAMEBUFFER,l),!n.isFramebuffer(l))throw"Invalid framebuffer";n.bindFramebuffer(n.FRAMEBUFFER,null);const o=n.checkFramebufferStatus(n.FRAMEBUFFER);switch(o){case n.FRAMEBUFFER_COMPLETE:break;case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+o}this.buffer={framebuf:l,renderbuf:r,texture:i[0],textures:i,depthTexture:a,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,n=null,i=Uint8Array,a=4,r=0){const l=e,o=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,c=new i(a),u=this.gl;return u.readBuffer(u.COLOR_ATTACHMENT0+r),u.readPixels(l,o,1,1,s||u.RGBA,n||u.UNSIGNED_BYTE,c,0),c}readArray(e=null,t=null,s=Uint8Array,n=4,i=0){const a=new s(this.buffer.width*this.buffer.height*n),r=this.gl;return r.readBuffer(r.COLOR_ATTACHMENT0+i),r.readPixels(0,0,this.buffer.width,this.buffer.height,e||r.RGBA,t||r.UNSIGNED_BYTE,a,0),a}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,n=t.canvas,i=t.imageData,a=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const r=this.buffer.width,l=this.buffer.height,o=l/2|0,c=4*r,u=new Uint8Array(4*r);for(let e=0;e<o;++e){const t=e*c,n=(l-e-1)*c;u.set(s.subarray(t,t+c)),s.copyWithin(t,n,n+c),s.set(u,n)}return i.data.set(s),a.putImageData(i,0,0),n}readImage(e){const t=this.gl,s=this._getImageDataCache(),n=s.pixelData,i=s.canvas,a=s.imageData,r=s.context,{width:l,height:o}=this.buffer;t.readPixels(0,0,l,o,t.RGBA,t.UNSIGNED_BYTE,n),a.data.set(n),r.putImageData(a,0,0),r.save(),r.globalCompositeOperation="copy",r.scale(1,-1),r.drawImage(i,0,-o,l,o),r.restore();let c=e.format||"png";return"jpeg"!==c&&"png"!==c&&"bmp"!==c&&(console.error("Unsupported image format: '"+c+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),c="png"),i.toDataURL(`image/${c}`)}_getImageDataCache(e=Uint8Array,t=4){const s=this.buffer.width,n=this.buffer.height;let i=this._imageDataCache;if(i&&(i.width===s&&i.height===n||(this._imageDataCache=null,i=null)),!i){const a=document.createElement("canvas"),r=a.getContext("2d");a.width=s,a.height=n,i={pixelData:new e(s*n*t),canvas:a,context:r,imageData:r.createImageData(s,n),width:s,height:n},this._imageDataCache=i}return i.context.resetTransform(),i}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(e=0){const t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(s){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+s]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(s){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+s]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;this.buffer.textures.forEach((t=>e.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class ze{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let n=s[e];return n||(n=new We(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=n),n}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Ke(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}const Ye=function(t,s){s=s||{};const n=new we(t),i=t.canvas.canvas,a=t.canvas.gl,r=!!s.transparent,l=s.alphaDepthMask,o=new e({});let c={},u={},p=!0,A=!0,f=!0,I=!0,y=!0,m=!0,v=!0,w=!0;const g=new ze(t);let E=!1;const T=new Fe(t),b=new Ve(t);function D(){p&&(!function(){for(let e in c)if(c.hasOwnProperty(e)){const t=c[e],s=t.drawableMap,n=t.drawableListPreCull;let i=0;for(let e in s)s.hasOwnProperty(e)&&(n[i++]=s[e]);n.length=i}}(),p=!1,A=!0),A&&(!function(){for(let e in c)if(c.hasOwnProperty(e)){const t=c[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),A=!1,f=!0),f&&function(){for(let e in c)if(c.hasOwnProperty(e)){const t=c[e],s=t.drawableListPreCull,n=t.drawableList;let i=0;for(let e=0,t=s.length;e<t;e++){const t=s[e];t.rebuildRenderFlags(),t.renderFlags.culled||(n[i++]=t)}n.length=i}}()}function P(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),n.reset(),n.backfaces=!0,n.frontface=!0,n.shadowViewMatrix=e.getShadowViewMatrix(),n.shadowProjMatrix=e.getShadowProjMatrix(),a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),a.clearColor(0,0,0,1),a.enable(a.DEPTH_TEST),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];!1!==s.visible&&s.castsShadow&&s.drawShadow&&(s.renderFlags.colorOpaque&&s.drawShadow(n))}}t.unbind()}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!Ke(a,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Ke(a,"WEBGL_compressed_texture_etc"),dxtSupported:!!Ke(a,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Ke(a,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Ke(a,"WEBGL_compressed_texture_pvrtc")&&!Ke(a,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){I=e,f=!0},this.setEdgesEnabled=function(e){y=e,f=!0},this.setSAOEnabled=function(e){m=e,f=!0},this.setPBREnabled=function(e){v=e,f=!0},this.setColorTextureEnabled=function(e){w=e,f=!0},this.needStateSort=function(){A=!0},this.shadowsDirty=function(){},this.imageDirty=function(){f=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){T.init(),b.init(),f=!0},this.addDrawable=function(e,t){const s=t.type;if(!s)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let n=c[s];n||(n={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},c[s]=n),n.count++,n.drawableMap[e]=t,u[e]=t,p=!0},this.removeDrawable=function(e){const t=u[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const s=t.type,n=c[s];--n.count<=0?delete c[s]:delete n.drawableMap[e],delete u[e],p=!0},this.getPickID=function(e){return o.addItem(e)},this.putPickID=function(e){o.removeItem(e)},this.clear=function(e){if(a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),r)a.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;a.clearColor(e[0],e[1],e[2],1)}a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT)},this.needsRender=function(){return f||p||A},this.render=function(e){(e=e||{}).force&&(f=!0),D(),f&&(!function(e){const s=t.sao;m&&s.possible&&function(e){const s=t.sao,i=g.getRenderBuffer("saoDepth",{depthTexture:!0});i.bind(),i.clear(),function(e){n.reset(),n.pass=e.pass,a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),a.clearColor(0,0,0,0),a.enable(a.DEPTH_TEST),a.frontFace(a.CCW),a.enable(a.CULL_FACE),a.depthMask(!0),!1!==e.clear&&a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];!0!==s.culled&&!1!==s.visible&&s.drawDepth&&s.saoEnabled&&(s.renderFlags.colorOpaque&&s.drawDepth(n))}}}(e),i.unbind();const r=g.getRenderBuffer("saoOcclusion");if(r.bind(),r.clear(),T.render(i),r.unbind(),s.blur){const e=g.getRenderBuffer("saoOcclusion2");e.bind(),e.clear(),b.render(i,r,0),e.unbind(),r.bind(),r.clear(),b.render(i,e,1),r.unbind()}}(e);(function(){let e=t._lightsState.lights;for(let t=0,s=e.length;t<s;t++){const s=e[t];s.castsShadow&&P(s)}})(),function(e){const s=[],i=[],o=[],u=[],h=[],p=[],A=[],f=[],E=[],T=[],b=[],D=[],P=[],R=[],C=[],_=[],B=t._lightsState.getAmbientColorAndIntensity();if(n.reset(),n.pass=e.pass,n.withSAO=!1,n.pbrEnabled=v&&!!t.pbrEnabled,n.colorTextureEnabled=w&&!!t.colorTextureEnabled,a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),r)a.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?B:t.canvas.backgroundColor;a.clearColor(e[0],e[1],e[2],1)}a.enable(a.DEPTH_TEST),a.frontFace(a.CCW),a.enable(a.CULL_FACE),a.depthMask(!0),a.lineWidth(1),n.lineWidth=1;const O=t.sao.possible;if(m&&O){const e=g.getRenderBuffer("saoOcclusion");n.occlusionTexture=e?e.getTexture():null}else n.occlusionTexture=null;let S,N,x;const L=Date.now();!1!==e.clear&&a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);let M=0,F=0,H=0,U=0,G=0,j=0,V=0,k=0,Q=0,W=0,z=0,K=0,Y=0,X=0,q=0,J=0;for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(S=0,N=t.length;S<N;S++){if(x=t[S],!0===x.culled||!1===x.visible)continue;const e=x.renderFlags;e.colorOpaque&&(m&&O&&x.saoEnabled?s[M++]=x:x.drawColorOpaque(n)),I&&e.colorTransparent&&(o[H++]=x),e.xrayedSilhouetteTransparent&&(A[V++]=x),e.xrayedSilhouetteOpaque&&(h[G++]=x),e.highlightedSilhouetteTransparent&&(b[z++]=x),e.highlightedSilhouetteOpaque&&(E[Q++]=x),e.selectedSilhouetteTransparent&&(C[q++]=x),e.selectedSilhouetteOpaque&&(P[Y++]=x),y&&(e.edgesOpaque&&(i[F++]=x),e.edgesTransparent&&(u[U++]=x)),e.selectedEdgesTransparent&&(_[J++]=x),e.selectedEdgesOpaque&&(R[X++]=x),e.xrayedEdgesTransparent&&(f[k++]=x),e.xrayedEdgesOpaque&&(p[j++]=x),e.highlightedEdgesTransparent&&(D[K++]=x),e.highlightedEdgesOpaque&&(T[W++]=x)}}if(M>0)for(n.withSAO=!0,S=0;S<M;S++)s[S].drawColorOpaque(n);if(F>0)for(S=0;S<F;S++)i[S].drawEdgesColorOpaque(n);if(G>0)for(S=0;S<G;S++)h[S].drawSilhouetteXRayed(n);if(j>0)for(S=0;S<j;S++)p[S].drawEdgesXRayed(n);if(V>0||k>0||H>0||U>0){if(a.enable(a.CULL_FACE),a.enable(a.BLEND),r?(a.blendEquation(a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA)),n.backfaces=!1,l||a.depthMask(!1),(H>0||U>0)&&a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),U>0)for(S=0;S<U;S++)x=u[S],x.drawEdgesColorTransparent(n);if(H>0)for(S=0;S<H;S++)x=o[S],x.drawColorTransparent(n);if(k>0)for(S=0;S<k;S++)f[S].drawEdgesXRayed(n);if(V>0)for(S=0;S<V;S++)A[S].drawSilhouetteXRayed(n);a.disable(a.BLEND),l||a.depthMask(!0)}if(Q>0||W>0){if(n.lastProgramId=null,t.highlightMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),W>0)for(S=0;S<W;S++)T[S].drawEdgesHighlighted(n);if(Q>0)for(S=0;S<Q;S++)E[S].drawSilhouetteHighlighted(n)}if(z>0||K>0||Q>0){if(n.lastProgramId=null,t.selectedMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),a.enable(a.BLEND),r?(a.blendEquation(a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),a.enable(a.CULL_FACE),K>0)for(S=0;S<K;S++)D[S].drawEdgesHighlighted(n);if(z>0)for(S=0;S<z;S++)b[S].drawSilhouetteHighlighted(n);a.disable(a.BLEND)}if(Y>0||X>0){if(n.lastProgramId=null,t.selectedMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),X>0)for(S=0;S<X;S++)R[S].drawEdgesSelected(n);if(Y>0)for(S=0;S<Y;S++)P[S].drawSilhouetteSelected(n)}if(q>0||J>0){if(n.lastProgramId=null,t.selectedMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),a.enable(a.CULL_FACE),a.enable(a.BLEND),r?(a.blendEquation(a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),J>0)for(S=0;S<J;S++)_[S].drawEdgesSelected(n);if(q>0)for(S=0;S<q;S++)C[S].drawSilhouetteSelected(n);a.disable(a.BLEND)}const Z=Date.now(),$=d.frame;$.renderTime=(Z-L)/1e3,$.drawElements=n.drawElements,$.drawArrays=n.drawArrays,$.useProgram=n.useProgram,$.bindTexture=n.bindTexture,$.bindArray=n.bindArray;const ee=ge.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<ee;e++)a.activeTexture(a.TEXTURE0+e);a.bindTexture(a.TEXTURE_CUBE_MAP,null),a.bindTexture(a.TEXTURE_2D,null);const te=ge.MAX_VERTEX_ATTRIBS;for(let e=0;e<te;e++)a.disableVertexAttribArray(e)}(e)}(e),d.frame.frameCount++,f=!1)},this.pick=function(){const e=h.vec3();h.mat4();const s=h.mat4(),r=h.vec3(),l=h.vec3([0,1,0]),u=new Te,p=h.vec2(),A=h.vec3(),d=h.vec3(),f=h.vec3();return h.vec3(),h.vec3(),function(I,y=u){let m;y.reset(),D();let v=null,w=null;y.pickSurface=I.pickSurface,I.canvasPos?(A[0]=I.canvasPos[0],A[1]=I.canvasPos[1],v=t.camera.viewMatrix,w=t.camera.projMatrix,y.canvasPos=I.canvasPos):(I.matrix?(v=I.matrix,w=t.camera.projMatrix):(d.set(I.origin||[0,0,0]),f.set(I.direction||[0,0,1]),m=h.addVec3(d,f,e),r[0]=Math.random(),r[1]=Math.random(),r[2]=Math.random(),h.normalizeVec3(r),h.cross3Vec3(f,r,l),v=h.lookAtMat4v(d,m,l,s),w=t.camera.projMatrix,y.origin=d,y.direction=f),A[0]=.5*i.clientWidth,A[1]=.5*i.clientHeight);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];s.setPickMatrices&&s.setPickMatrices(v,w)}}const E=g.getRenderBuffer("pick",{size:[1,1]});E.bind();const T=function(e,s,i,r,l,u){const h=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=u.origin,n.pickViewMatrix=i,n.pickProjMatrix=r,n.pickInvisible=!!l.pickInvisible,n.pickClipPos=[_(s[0]*h,a.drawingBufferWidth),B(s[1]*h,a.drawingBufferHeight)],a.viewport(0,0,1,1),a.depthMask(!0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);const p=l.includeEntityIds,A=l.excludeEntityIds;for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];!s.drawPickMesh||!0!==l.pickInvisible&&!1===s.visible||!1===s.pickable||(p&&!p[s.id]||A&&A[s.id]||s.drawPickMesh(n))}}const d=e.read(0,0),f=d[0]+(d[1]<<8)+(d[2]<<16)+(d[3]<<24);if(f<0)return;return o.items[f]}(E,A,v,w,I,y);if(!T)return E.unbind(),null;const b=T.delegatePickedEntity?T.delegatePickedEntity():T;return b?(I.pickSurface&&(T.canPickTriangle&&T.canPickTriangle()?(!function(e,s,i,r,l,o){if(!s.drawPickTriangles)return;const c=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=o.origin,n.pickViewMatrix=r,n.pickProjMatrix=l,n.pickClipPos=[_(i[0]*c,a.drawingBufferWidth),B(i[1]*c,a.drawingBufferHeight)],a.viewport(0,0,1,1),a.clearColor(0,0,0,0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT),s.drawPickTriangles(n);const u=e.read(0,0);let h=u[0]+256*u[1]+256*u[2]*256+256*u[3]*256*256;h*=3,o.primIndex=h}(E,T,A,v,w,y),T.pickTriangleSurface(v,w,y),y.pickSurfacePrecision=!1):T.canPickWorldPos&&T.canPickWorldPos()&&(p[0]=t.camera.project.near,p[1]=t.camera.project.far,R(E,T,A,v,w,p,y),!1!==I.pickSurfaceNormal&&function(e,s,i,r,l,o){const c=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=o.origin,n.pickViewMatrix=r,n.pickProjMatrix=l,n.pickClipPos=[_(i[0]*c,a.drawingBufferWidth),B(i[1]*c,a.drawingBufferHeight)];const u=g.getRenderBuffer("pick-normal",{size:[3,3]});u.bind(a.RGBA32I),a.viewport(0,0,u.size[0],u.size[1]),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.DEPTH_BUFFER_BIT),a.clearBufferiv(a.COLOR,0,new Int32Array([0,0,0,0])),s.drawPickNormals(n);const p=u.read(1,1,a.RGBA_INTEGER,a.INT,Int32Array,4);u.unbind();const A=[p[0]/h.MAX_INT,p[1]/h.MAX_INT,p[2]/h.MAX_INT];h.normalizeVec3(A),o.worldNormal=A}(0,T,A,v,w,y),y.pickSurfacePrecision=!1)),E.unbind(),y.entity=b,y):(E.unbind(),null)}}();const R=function(){const e=h.vec4(),s=h.vec4(),r=h.vec4(),l=h.vec4(),o=h.vec4(),c=h.mat4(),u=h.mat4(),p=h.mat4();return function(A,d,f,I,y,m,v){const w=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=v.origin,n.pickViewMatrix=I,n.pickProjMatrix=y,n.pickZNear=m[0],n.pickZFar=m[1],n.pickElementsCount=d.pickElementsCount,n.pickElementsOffset=d.pickElementsOffset,n.pickClipPos=[_(f[0]*w,a.drawingBufferWidth),B(f[1]*w,a.drawingBufferHeight)],a.viewport(0,0,1,1),a.clearColor(0,0,0,0),a.depthMask(!0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT),d.drawPickDepths(n);const g=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],s=[1/16777216,1/65536,1/256,1];return h.dotVec4(t,s)}(A.read(0,0)),E=(f[0]-i.clientWidth/2)/(i.clientWidth/2),T=-(f[1]-i.clientHeight/2)/(i.clientHeight/2),b=d.origin;let D;if(b){const e=G(I,b,c);D=h.mulMat4(y,e,u)}else D=h.mulMat4(y,I,u);const P=h.inverseMat4(D,p);e[0]=E,e[1]=T,e[2]=-1,e[3]=1;let R=h.transformVec4(P,e);R=h.mulVec4Scalar(R,1/R[3]),s[0]=E,s[1]=T,s[2]=1,s[3]=1;let C=h.transformVec4(P,s);C=h.mulVec4Scalar(C,1/C[3]);const O=h.subVec3(C,R,r),S=h.addVec3(R,h.mulVec4Scalar(O,g,l),o);b&&h.addVec3(S,b),v.worldPos=S}}();function C(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(let t in c){const s=c[t].drawableList;for(let t=0,n=s.length;t<n;t++){const n=s[t];n.drawSnapDepths&&!n.culled&&n.visible&&n.pickable&&n.drawSnapDepths(e)}}return e.snapPickLayerParams}function _(e,t){return e/t*2-1}function B(e,t){return 1-e/t*2}this.snapPick=function(){const e=new Te;return function(s,i,r,l,u=e){if(!r&&!l)return this.pick({canvasPos:s,pickSurface:!0});const p=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickZNear=t.camera.project.near,n.pickZFar=t.camera.project.far,i=i||30;const A=g.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*i+1,2*i+1]});n.snapVectorA=[_(s[0]*p,a.drawingBufferWidth),B(s[1]*p,a.drawingBufferHeight)],n.snapInvVectorAB=[a.drawingBufferWidth/(2*i),a.drawingBufferHeight/(2*i)],A.bind(a.RGBA32I,a.RGBA32I,a.RGBA8UI),a.viewport(0,0,A.size[0],A.size[1]),a.enable(a.DEPTH_TEST),a.frontFace(a.CCW),a.disable(a.CULL_FACE),a.depthMask(!0),a.disable(a.BLEND),a.depthFunc(a.LEQUAL),a.clear(a.DEPTH_BUFFER_BIT),a.clearBufferiv(a.COLOR,0,new Int32Array([0,0,0,0])),a.clearBufferiv(a.COLOR,1,new Int32Array([0,0,0,0])),a.clearBufferuiv(a.COLOR,2,new Uint32Array([0,0,0,0]));const d=t.camera.viewMatrix,f=t.camera.projMatrix;for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];s.setPickMatrices&&s.setPickMatrices(d,f)}}a.drawBuffers([a.COLOR_ATTACHMENT0,a.COLOR_ATTACHMENT1,a.COLOR_ATTACHMENT2]);const I=function(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(let t in c){const s=c[t].drawableList;for(let t=0,n=s.length;t<n;t++){const n=s[t];n.drawSnapInitDepthBuf&&!n.culled&&n.visible&&n.pickable&&n.drawSnapInitDepthBuf(e)}}return e.snapPickLayerParams}(n),y=[];n.snapPickLayerParams=y,a.depthMask(!1),a.drawBuffers([a.COLOR_ATTACHMENT0]),r&&l?(n.snapMode="edge",C(n),n.snapMode="vertex",n.snapPickLayerNumber++,C(n)):(n.snapMode=r?"vertex":"edge",C(n)),a.depthMask(!0);const m=A.readArray(a.RGBA_INTEGER,a.INT,Int32Array,4),v=A.readArray(a.RGBA_INTEGER,a.INT,Int32Array,4,1),w=A.readArray(a.RGBA_INTEGER,a.UNSIGNED_INT,Uint32Array,4,2);A.unbind();let E=null;const T=4*i+i*A.size[0]*4,b=m.slice(T,T+4),D=v.slice(T,T+4),P=w.slice(T,T+4);if(0!==b[3]){const e=I[Math.abs(b[3])%I.length],t=e.origin,s=e.coordinateScale;E=[b[0]*s[0]+t[0],b[1]*s[1]+t[1],b[2]*s[2]+t[2]],h.normalizeVec3([D[0]/h.MAX_INT,D[1]/h.MAX_INT,D[2]/h.MAX_INT]);const n=P[0]+(P[1]<<8)+(P[2]<<16)+(P[3]<<24);o.items[n]}let R=[];for(let e=0;e<m.length;e+=4)if(m[e+3]>0){const t=Math.floor(e/4),s=A.size[0],n=t%s-Math.floor(s/2),i=Math.floor(t/s)-Math.floor(s/2),a=Math.sqrt(Math.pow(n,2)+Math.pow(i,2));R.push({x:n,y:i,dist:a,isVertex:r&&l?m[e+3]>y.length/2:r,result:[m[e+0],m[e+1],m[e+2],m[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[w[e+0],w[e+1],w[e+2],w[e+3]]})}let O=null,S=null,N=null,x=null;if(R.length>0){R.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),x=R[0].isVertex?"vertex":"edge";const e=R[0].result,t=R[0].normal,s=R[0].id,n=y[e[3]],i=n.origin,a=n.coordinateScale;S=h.normalizeVec3([t[0]/h.MAX_INT,t[1]/h.MAX_INT,t[2]/h.MAX_INT]),O=[e[0]*a[0]+i[0],e[1]*a[1]+i[1],e[2]*a[2]+i[2]],N=o.items[s[0]+(s[1]<<8)+(s[2]<<16)+(s[3]<<24)]}if(null===E&&null==O)return null;let L=null;null!==O&&(L=t.camera.projectWorldPos(O));const M=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return u.reset(),u.snappedToEdge="edge"===x,u.snappedToVertex="vertex"===x,u.worldPos=O,u.worldNormal=S,u.entity=M,u.canvasPos=s,u.snappedCanvasPos=L||s,u}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Le(t,g),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){D(),this._occlusionTester.bindRenderBuf(),n.reset(),n.backfaces=!0,n.frontface=!0,a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),a.clearColor(0,0,0,0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];s.drawOcclusion&&!0!==s.culled&&!1!==s.visible&&!1!==s.pickable&&s.drawOcclusion(n)}}this._occlusionTester.drawMarkers(n),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,s,n){const i=g.getRenderBuffer("snapshot");let a,r,l,o;for(i.bind(),i.clear(),this.render({force:!0,opaqueOnly:n}),r=0;r<s;r++)l=2*r,o=4*r,a=i.read(e[l],e[l+1]),t[o]=a[0],t[o+1]=a[1],t[o+2]=a[2],t[o+3]=a[3];i.unbind(),f=!0},this.beginSnapshot=function(e={}){const t=g.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),E=!0},this.renderSnapshot=function(){if(!E)return;g.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),f=!0},this.readSnapshot=function(e){return g.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return g.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){if(!E)return;g.getRenderBuffer("snapshot").unbind(),E=!1},this.destroy=function(){c={},u={},g.destroy(),T.destroy(),b.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class Xe extends _{constructor(e,t={}){super(e,t),this.KEY_BACKSPACE=8,this.KEY_TAB=9,this.KEY_ENTER=13,this.KEY_SHIFT=16,this.KEY_CTRL=17,this.KEY_ALT=18,this.KEY_PAUSE_BREAK=19,this.KEY_CAPS_LOCK=20,this.KEY_ESCAPE=27,this.KEY_PAGE_UP=33,this.KEY_PAGE_DOWN=34,this.KEY_END=35,this.KEY_HOME=36,this.KEY_LEFT_ARROW=37,this.KEY_UP_ARROW=38,this.KEY_RIGHT_ARROW=39,this.KEY_DOWN_ARROW=40,this.KEY_INSERT=45,this.KEY_DELETE=46,this.KEY_NUM_0=48,this.KEY_NUM_1=49,this.KEY_NUM_2=50,this.KEY_NUM_3=51,this.KEY_NUM_4=52,this.KEY_NUM_5=53,this.KEY_NUM_6=54,this.KEY_NUM_7=55,this.KEY_NUM_8=56,this.KEY_NUM_9=57,this.KEY_A=65,this.KEY_B=66,this.KEY_C=67,this.KEY_D=68,this.KEY_E=69,this.KEY_F=70,this.KEY_G=71,this.KEY_H=72,this.KEY_I=73,this.KEY_J=74,this.KEY_K=75,this.KEY_L=76,this.KEY_M=77,this.KEY_N=78,this.KEY_O=79,this.KEY_P=80,this.KEY_Q=81,this.KEY_R=82,this.KEY_S=83,this.KEY_T=84,this.KEY_U=85,this.KEY_V=86,this.KEY_W=87,this.KEY_X=88,this.KEY_Y=89,this.KEY_Z=90,this.KEY_LEFT_WINDOW=91,this.KEY_RIGHT_WINDOW=92,this.KEY_SELECT_KEY=93,this.KEY_NUMPAD_0=96,this.KEY_NUMPAD_1=97,this.KEY_NUMPAD_2=98,this.KEY_NUMPAD_3=99,this.KEY_NUMPAD_4=100,this.KEY_NUMPAD_5=101,this.KEY_NUMPAD_6=102,this.KEY_NUMPAD_7=103,this.KEY_NUMPAD_8=104,this.KEY_NUMPAD_9=105,this.KEY_MULTIPLY=106,this.KEY_ADD=107,this.KEY_SUBTRACT=109,this.KEY_DECIMAL_POINT=110,this.KEY_DIVIDE=111,this.KEY_F1=112,this.KEY_F2=113,this.KEY_F3=114,this.KEY_F4=115,this.KEY_F5=116,this.KEY_F6=117,this.KEY_F7=118,this.KEY_F8=119,this.KEY_F9=120,this.KEY_F10=121,this.KEY_F11=122,this.KEY_F12=123,this.KEY_NUM_LOCK=144,this.KEY_SCROLL_LOCK=145,this.KEY_SEMI_COLON=186,this.KEY_EQUAL_SIGN=187,this.KEY_COMMA=188,this.KEY_DASH=189,this.KEY_PERIOD=190,this.KEY_FORWARD_SLASH=191,this.KEY_GRAVE_ACCENT=192,this.KEY_OPEN_BRACKET=219,this.KEY_BACK_SLASH=220,this.KEY_CLOSE_BRACKET=221,this.KEY_SINGLE_QUOTE=222,this.KEY_SPACE=32,this.element=t.element,this.altDown=!1,this.ctrlDown=!1,this.mouseDownLeft=!1,this.mouseDownMiddle=!1,this.mouseDownRight=!1,this.keyDown=[],this.enabled=!0,this.keyboardEnabled=!0,this.mouseover=!1,this.mouseCanvasPos=h.vec2(),this._keyboardEventsElement=t.keyboardEventsElement||document,this._bindEvents()}_bindEvents(){if(this._eventsBound)return;this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,s)=>{if(!this.enabled)return;const n=Math.max(-1,Math.min(1,40*-e.deltaY));t(n)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(n=>{e>=n[0]-s&&e<=n[0]+s&&t>=n[1]-s&&t<=n[1]+s&&this.fire("mouseclicked",n,!0)}))}this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,n=0;for(;t.offsetParent;)s+=t.offsetLeft,n+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-n}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const qe=new e({});class Je{constructor(e){this.id=qe.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){qe.removeItem(this.id)}}class Ze extends _{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Je({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],s=e[3];this._state.boundary=[0,0,t,s],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class $e extends _{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],s=this._fovAxis;let n=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(n/=t),n=Math.min(n,120),h.perspectiveMat4(n*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class et extends _{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.canvas.boundary,n=s[2],i=s[3],a=n/i;let r,l,o,c;n>i?(r=-t,l=t,o=t/a,c=-t/a):(r=-t*a,l=t*a,o=t,c=-t),h.orthoMat4c(r,l,c,o,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class tt extends _{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){h.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class st extends _{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy()}}const nt=h.vec3(),it=h.vec3(),at=h.vec3(),rt=h.vec3(),lt=h.vec3(),ot=h.vec3(),ct=h.vec4(),ut=h.vec4(),ht=h.vec4(),pt=h.mat4(),At=h.mat4(),dt=h.vec3(),ft=h.vec3(),It=h.vec3(),yt=h.vec3();class mt extends _{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Je({deviceMatrix:h.mat4(),hasDeviceMatrix:!1,matrix:h.mat4(),normalMatrix:h.mat4(),inverseMatrix:h.mat4()}),this._perspective=new $e(this),this._ortho=new et(this),this._frustum=new tt(this),this._customProjection=new st(this),this._project=this._perspective,this._eye=h.vec3([0,0,10]),this._look=h.vec3([0,0,0]),this._up=h.vec3([0,1,0]),this._worldUp=h.vec3([0,1,0]),this._worldRight=h.vec3([1,0,0]),this._worldForward=h.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(h.subVec3(this._eye,this._look,dt),h.normalizeVec3(dt,ft),h.mulVec3Scalar(ft,1e3,It),h.addVec3(this._look,It,yt),t=yt):t=this._eye,e.hasDeviceMatrix?(h.lookAtMat4v(t,this._look,this._up,At),h.mulMat4(e.deviceMatrix,At,e.matrix)):h.lookAtMat4v(t,this._look,this._up,e.matrix),h.inverseMat4(this._state.matrix,this._state.inverseMatrix),h.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=h.subVec3(this._eye,this._look,nt);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=h.transformPoint3(pt,t,it),this.eye=h.addVec3(this._look,t,at),this.up=h.transformPoint3(pt,this._up,rt)}orbitPitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._eye,this._look,nt);const s=h.cross3Vec3(h.normalizeVec3(t,it),h.normalizeVec3(this._up,at));h.rotationMat4v(.0174532925*e,s,pt),t=h.transformPoint3(pt,t,rt),this.up=h.transformPoint3(pt,this._up,lt),this.eye=h.addVec3(t,this._look,ot)}yaw(e){let t=h.subVec3(this._look,this._eye,nt);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=h.transformPoint3(pt,t,it),this.look=h.addVec3(t,this._eye,at),this._gimbalLock&&(this.up=h.transformPoint3(pt,this._up,rt))}pitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._look,this._eye,nt);const s=h.cross3Vec3(h.normalizeVec3(t,it),h.normalizeVec3(this._up,at));h.rotationMat4v(.0174532925*e,s,pt),this.up=h.transformPoint3(pt,this._up,ot),t=h.transformPoint3(pt,t,rt),this.look=h.addVec3(t,this._eye,lt)}pan(e){const t=h.subVec3(this._eye,this._look,nt),s=[0,0,0];let n;if(0!==e[0]){const i=h.cross3Vec3(h.normalizeVec3(t,[]),h.normalizeVec3(this._up,it));n=h.mulVec3Scalar(i,e[0]),s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]}0!==e[1]&&(n=h.mulVec3Scalar(h.normalizeVec3(this._up,at),e[1]),s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]),0!==e[2]&&(n=h.mulVec3Scalar(h.normalizeVec3(t,rt),e[2]),s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]),this.eye=h.addVec3(this._eye,s,lt),this.look=h.addVec3(this._look,s,ot)}zoom(e){const t=h.subVec3(this._eye,this._look,nt),s=Math.abs(h.lenVec3(t,it)),n=Math.abs(s+e);if(n<.5)return;const i=h.normalizeVec3(t,at);this.eye=h.addVec3(this._look,h.mulVec3Scalar(i,n),rt)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=h.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return h.lenVec3(h.subVec3(this._look,this._eye,nt))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=ct,s=ut,n=ht;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,h.mulMat4v4(this.viewMatrix,t,s),h.mulMat4v4(this.projMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1;const i=this.scene.canvas.canvas,a=i.offsetWidth/2,r=i.offsetHeight/2;return[n[0]*a+a,n[1]*r+r]}destroy(){super.destroy(),this._state.destroy()}}class vt extends _{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class wt extends vt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,n=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=n.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Je({type:"dir",dir:h.vec3([1,1,1]),color:h.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=h.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,n=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],i=[0,1,0];h.lookAtMat4v(n,s,i,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=h.identityMat4()),h.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new We(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class gt extends vt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:h.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Et extends _{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var Tt=function(){const e=[],t=[],s=[],n=[],i=[];let a=0;const r=new Uint16Array(3),l=new Uint16Array(3),o=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3();return function(y,m,v,w){!function(i,a){const r={};let l,o,c,u;const h=Math.pow(10,4);let p,A,d=0;for(p=0,A=i.length;p<A;p+=3)l=i[p],o=i[p+1],c=i[p+2],u=Math.round(l*h)+"_"+Math.round(o*h)+"_"+Math.round(c*h),void 0===r[u]&&(r[u]=d/3,e[d++]=l,e[d++]=o,e[d++]=c),t[p/3]=r[u];for(p=0,A=a.length;p<A;p++)n[p]=t[a[p]],s[n[p]]=a[p]}(y,m),function(t,s){a=0;for(let y=0,m=t;y<m;y+=3){const t=3*n[y],m=3*n[y+1],v=3*n[y+2];s?(r[0]=e[t],r[1]=e[t+1],r[2]=e[t+2],l[0]=e[m],l[1]=e[m+1],l[2]=e[m+2],o[0]=e[v],o[1]=e[v+1],o[2]=e[v+2],h.decompressPosition(r,s,c),h.decompressPosition(l,s,u),h.decompressPosition(o,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[m],u[1]=e[m+1],u[2]=e[m+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,A),h.subVec3(c,u,d),h.cross3Vec3(A,d,f),h.normalizeVec3(f,I);const w=i[a]||(i[a]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],a++}}(m.length,v);const g=[],E=Math.cos(h.DEGTORAD*w),T={};let b,D,P,R,C,_,B,O,S,N,x,L=!1;for(let e=0,t=m.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=n[e+s],D=n[e+(s+1)%3],P=Math.min(b,D),R=Math.max(b,D),C=P+","+R,void 0===T[C]?T[C]={index1:P,index2:R,face1:t,face2:void 0}:T[C].face2=t}for(C in T)_=T[C],void 0!==_.face2&&(B=i[_.face1].normal,O=i[_.face2].normal,S=h.dotVec3(B,O),S>E)||(N=s[_.index1],x=s[_.index2],(!L&&N>65535||x>65535)&&(L=!0),g.push(N),g.push(x));return L?new Uint32Array(g):new Uint16Array(g)}}();const bt=function(){const e=h.mat4(),t=h.mat4();return function(s,n){n=n||h.mat4();const i=s[0],a=s[1],r=s[2],l=s[3]-i,o=s[4]-a,c=s[5]-r,u=65535;return h.identityMat4(e),h.translationMat4v(s,e),h.identityMat4(t),h.scalingMat4v([l/u,o/u,c/u],t),h.mulMat4(e,t,n),n}}();var Dt=function(){const e=h.mat4(),t=h.mat4();return function(s,n,i){const a=new Uint16Array(s.length),r=new Float32Array([i[0]!==n[0]?65535/(i[0]-n[0]):0,i[1]!==n[1]?65535/(i[1]-n[1]):0,i[2]!==n[2]?65535/(i[2]-n[2]):0]);let l;for(l=0;l<s.length;l+=3)a[l+0]=Math.max(0,Math.min(65535,Math.floor((s[l+0]-n[0])*r[0]))),a[l+1]=Math.max(0,Math.min(65535,Math.floor((s[l+1]-n[1])*r[1]))),a[l+2]=Math.max(0,Math.min(65535,Math.floor((s[l+2]-n[2])*r[2])));h.identityMat4(e),h.translationMat4v(n,e),h.identityMat4(t),h.scalingMat4v([(i[0]-n[0])/65535,(i[1]-n[1])/65535,(i[2]-n[2])/65535],t);return{quantized:a,decodeMatrix:h.mulMat4(e,t,h.identityMat4())}}}();var Pt=function(){const e=h.mat3(),t=h.mat3();return function(s,n,i){const a=new Uint16Array(s.length),r=new Float32Array([65535/(i[0]-n[0]),65535/(i[1]-n[1])]);let l;for(l=0;l<s.length;l+=2)a[l+0]=Math.max(0,Math.min(65535,Math.floor((s[l+0]-n[0])*r[0]))),a[l+1]=Math.max(0,Math.min(65535,Math.floor((s[l+1]-n[1])*r[1])));h.identityMat3(e),h.translationMat3v(n,e),h.identityMat3(t),h.scalingMat3v([(i[0]-n[0])/65535,(i[1]-n[1])/65535],t);return{quantized:a,decodeMatrix:h.mulMat3(e,t,h.identityMat3())}}}();function Rt(e,t,s,n){let i=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),a=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(a))*(i>=0?1:-1),t=(1-Math.abs(i))*(a>=0?1:-1);i=e,a=t}return new Int8Array([Math[s](127.5*i+(i<0?-1:0)),Math[n](127.5*a+(a<0?-1:0))])}function Ct(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}function _t(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const Bt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let n,i;for(n=0;n<3;n++)t[n]=Number.MAX_VALUE,s[n]=-Number.MAX_VALUE;for(n=0;n<e.length;n+=3)for(i=0;i<3;i++)t[i]=Math.min(t[i],e[n+i]),s[i]=Math.max(s[i],e[n+i]);return{min:t,max:s}},createPositionsDecodeMatrix:bt,compressPositions:Dt,compressPosition:function(e,t,s){const n=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);s[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*n[0]))),s[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*n[1]))),s[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*n[2])))},decompressPositions:function(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[12],s[n+1]=e[n+1]*t[5]+t[13],s[n+2]=e[n+2]*t[10]+t[14];return s},decompressPosition:function(e,t,s){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s},decompressAABB:function(e,t,s=e){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s[3]=e[3]*t[0]+t[12],s[4]=e[4]*t[5]+t[13],s[5]=e[5]*t[10]+t[14],s},getUVBounds:function(e){const t=new Float32Array(2),s=new Float32Array(2);let n,i;for(n=0;n<2;n++)t[n]=Number.MAX_VALUE,s[n]=-Number.MAX_VALUE;for(n=0;n<e.length;n+=2)for(i=0;i<2;i++)t[i]=Math.min(t[i],e[n+i]),s[i]=Math.max(s[i],e[n+i]);return{min:t,max:s}},compressUVs:Pt,decompressUVs:function(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[6],s[n+1]=e[n+1]*t[4]+t[7];return s},decompressUV:function(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let s,n,i,a,r;for(let l=0;l<e.length;l+=3)i=s=Rt(e,l,"floor","floor"),n=Ct(s),a=r=_t(e,l,n),s=Rt(e,l,"ceil","floor"),n=Ct(s),a=_t(e,l,n),a>r&&(i=s,r=a),s=Rt(e,l,"floor","ceil"),n=Ct(s),a=_t(e,l,n),a>r&&(i=s,r=a),s=Rt(e,l,"ceil","ceil"),n=Ct(s),a=_t(e,l,n),a>r&&(i=s,r=a),t[l]=i[0],t[l+1]=i[1];return t},decompressNormals:function(e,t){for(let s=0,n=0,i=e.length;s<i;s+=2){let i=e[s+0],a=e[s+1];i=(2*i+1)/255,a=(2*a+1)/255;const r=1-Math.abs(i)-Math.abs(a);r<0&&(i=(1-Math.abs(a))*(i>=0?1:-1),a=(1-Math.abs(i))*(a>=0?1:-1));const l=Math.sqrt(i*i+a*a+r*r);t[n+0]=i/l,t[n+1]=a/l,t[n+2]=r/l,n+=3}return t},decompressNormal:function(e,t){let s=e[0],n=e[1];s=(2*s+1)/255,n=(2*n+1)/255;const i=1-Math.abs(s)-Math.abs(n);i<0&&(s=(1-Math.abs(n))*(s>=0?1:-1),n=(1-Math.abs(s))*(n>=0?1:-1));const a=Math.sqrt(s*s+n*n+i*i);return t[0]=s/a,t[1]=n/a,t[2]=i/a,t}},Ot=d.memory,St=h.AABB3();class Nt extends Et{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Je({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Bt.getPositionsBounds(t.positions),n=Bt.compressPositions(t.positions,e.min,e.max);s.positions=n.quantized,s.positionsDecodeMatrix=n.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Bt.getUVBounds(t.uv),n=Bt.compressUVs(t.uv,e.min,e.max);s.uv=n.quantized,s.uvDecodeMatrix=n.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=Bt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Ot.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Ot.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Ot.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new Oe(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),Ot.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Ot.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Oe(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Ot.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=Tt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),Ot.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=h.buildPickTriangles(e.positions,e.indices,e.compressGeometry),n=s.positions,i=s.colors;this._pickTrianglePositionsBuf=new Oe(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,4,t.STATIC_DRAW,!0),Ot.positions+=this._pickTrianglePositionsBuf.numItems,Ot.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Bt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=Bt.getPositionsBounds(e),n=Bt.compressPositions(e,s.min,s.max);e=n.quantized,t.positionsDecodeMatrix=n.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Bt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Bt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=h.AABB3()),h.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=h.OBB3()),h.positions3ToAABB3(this._state.positions,St,this._state.positionsDecodeMatrix),h.AABB3ToOBB3(St,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Ot.meshes--}}function xt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let n=e.zSize||1;n<0&&(console.error("negative zSize not allowed - will invert"),n*=-1);const i=e.center,a=i?i[0]:0,r=i?i[1]:0,l=i?i[2]:0,o=-t+a,c=-s+r,u=-n+l,h=t+a,p=s+r,A=n+l;return m.apply(e,{positions:[h,p,A,o,p,A,o,c,A,h,c,A,h,p,A,h,c,A,h,c,u,h,p,u,h,p,A,h,p,u,o,p,u,o,p,A,o,p,A,o,p,u,o,c,u,o,c,A,o,c,u,h,c,u,h,c,A,o,c,A,h,c,u,o,c,u,o,p,u,h,p,u],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Lt extends _{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const Mt={opaque:0,mask:1,blend:2},Ft=["opaque","mask","blend"];class Ht extends Lt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"PhongMaterial",ambient:h.vec3([1,1,1]),diffuse:h.vec3([1,1,1]),specular:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Mt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Ft[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Ut={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Gt extends Lt{get type(){return"EmphasisMaterial"}get presets(){return Ut}constructor(e,t={}){super(e,t),this._state=new Je({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Ut[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ut).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const jt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Vt extends Lt{get type(){return"EdgeMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new Je({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=jt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(jt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const kt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Qt extends _{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=h.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return kt}set units(e){e||(e="meters");kt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=h.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=h.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class Wt extends _{constructor(e,t={}){super(e,t),this._supported=ge.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const zt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Kt extends Lt{get type(){return"PointsMaterial"}get presets(){return zt}constructor(e,t={}){super(e,t),this._state=new Je({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=zt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(zt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Xt extends Lt{get type(){return"LinesMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new Je({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function qt(e,t){const s={};let n,i;for(let a=0,r=t.length;a<r;a++)n=t[a],i=e.components[n],i?i.isEntity?s[n]=!0:e.warn("pick(): Component is not an Entity: "+n):e.warn("pick(): Component not found: "+n);return s}class Jt extends _{get type(){return"Scene"}constructor(e,t={}){super(null,t);const s=t.canvasElement||document.getElementById(t.canvasId);if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";this._tickifiedFunctions={};const n=!!t.transparent,i=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new ve(this,{dontClear:!0,canvas:s,spinnerElementId:t.spinnerElementId,transparent:n,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Ye(this,{transparent:n,alphaDepthMask:i}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,n=t.length;e<n;e++)s.push("cp");return s.push(";"),e=s.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let s=0,n=this.sectionPlanes.length;s<n;s++)if(this.sectionPlanes[s].id===t.id)return this.sectionPlanes.splice(s,1),void(e=null)}},this._lightsState=new function(){const e=h.vec4([0,0,0,0]),t=h.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,n=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let n;for(let s=0,i=t.length;s<i;s++)n=t[s],e.push("/"),e.push(n.type),e.push("world"===n.space?"w":"v"),n.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),n=null,s=null},this.removeLight=function(e){for(let t=0,i=this.lights.length;t<i;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),n&&n.id===e.id&&(n=null),void(s=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),s=null},this.removeReflectionMap=function(e){for(let t=0,n=this.reflectionMaps.length;t<n;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(s=null)},this.addLightMap=function(e){this.lightMaps.push(e),s=null},this.removeLightMap=function(e){for(let t=0,n=this.lightMaps.length;t<n;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(s=null)},this.getAmbientColorAndIntensity=function(){if(!n)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){n=t;break}}if(n){const e=n.color,s=n.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=s,t}return e}},this.input=new Xe(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new Qt(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Wt(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,R._addScene(this),this._initDefaults(),this._viewport=new Ze(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new mt(this,{id:"default.camera",dontClear:!0}),new gt(this,{color:[1,1,1],intensity:.7}),new wt(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new wt(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+m.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=h.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const n=this.types[s];n&&(delete n[t],m.isEmptyObject(n)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&R.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,n=this._clearEachPass;let i,a;for(i=0;i<s;i++)t.pass=i,this.fire("rendering",t,!0),a=n||0===i,this._renderer.render({pass:i,clear:a,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=h.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||xt(Nt)}get material(){return this.components["default.material"]||new Ht(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new Gt(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new Gt(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new Gt(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new Vt(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Kt(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new Xt(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=h.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=h.AABB3());let e,t=h.MAX_DOUBLE,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MIN_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE;const l=this._collidables;let o,c=!1;for(const u in l)if(l.hasOwnProperty(u)){if(o=l[u],!1===o.collidable)continue;e=o.aabb,e[0]<t&&(t=e[0]),e[1]<s&&(s=e[1]),e[2]<n&&(n=e[2]),e[3]>i&&(i=e[3]),e[4]>a&&(a=e[4]),e[5]>r&&(r=e[5]),c=!0}c||(t=-100,s=-100,n=-100,i=100,a=100,r=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=n,this._aabb[3]=i,this._aabb[4]=a,this._aabb[5]=r,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const s=e.includeEntities||e.include;s&&(e.includeEntityIds=qt(this,s));const n=e.excludeEntities||e.exclude;return n&&(e.excludeEntityIds=qt(this,n)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t<s;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,s=e.length;t<s;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,s=e.length;t<s;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,s=e.length;t<s;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(m.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MAX_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE,l=h.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const o=e.aabb;o[0]<s&&(s=o[0]),o[1]<n&&(n=o[1]),o[2]<i&&(i=o[2]),o[3]>a&&(a=o[3]),o[4]>r&&(r=o[4]),o[5]>l&&(l=o[5]),t=!0}})),t){const e=h.AABB3();return e[0]=s,e[1]=n,e[2]=i,e[3]=a,e[4]=r,e[5]=l,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){m.isString(e)&&(e=[e]);let s=!1;for(let n=0,i=e.length;n<i;n++){const i=e[n];let a=this.objects[i];if(a)s=t(a)||s;else{const e=this.modelIds;for(let n=0,r=e.length;n<r;n++){const r=e[n],l=h.globalizeObjectId(r,i);a=this.objects[l],a&&(s=t(a)||s)}}}return s}tickify(e){const t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;let s,n=0,i=0;const a=function(...e){s=e,i++},r=this.on("tick",(()=>{i>n&&(n=i,e(...s))}));return this._tickifiedFunctions[t]={tickSubId:r,wrapperFunc:a},a}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const Zt=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene._lightsState,i=e._geometry._state,a=e._state.billboard,r=e._state.stationary,l=s.sectionPlanes.length>0,o=!!i.compressGeometry,c=[];c.push("#version 300 es"),c.push("// Lambertian drawing vertex shader"),c.push("in vec3 position;"),c.push("uniform mat4 modelMatrix;"),c.push("uniform mat4 viewMatrix;"),c.push("uniform mat4 projMatrix;"),c.push("uniform vec4 colorize;"),c.push("uniform vec3 offset;"),o&&c.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(c.push("uniform float logDepthBufFC;"),c.push("out float vFragDepth;"),c.push("bool isPerspectiveMatrix(mat4 m) {"),c.push(" return (m[2][3] == - 1.0);"),c.push("}"),c.push("out float isPerspective;"));l&&c.push("out vec4 vWorldPosition;");if(c.push("uniform vec4 lightAmbient;"),c.push("uniform vec4 materialColor;"),c.push("uniform vec3 materialEmissive;"),i.normalsBuf){c.push("in vec3 normal;"),c.push("uniform mat4 modelNormalMatrix;"),c.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(c.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&c.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&c.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(c.push("uniform vec3 lightPos"+e+";"),c.push("uniform vec3 lightDir"+e+";")))}o&&(c.push("vec3 octDecode(vec2 oct) {"),c.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),c.push(" if (v.z < 0.0) {"),c.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),c.push(" }"),c.push(" return normalize(v);"),c.push("}"))}c.push("out vec4 vColor;"),"points"===i.primitiveName&&c.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(c.push("void billboard(inout mat4 mat) {"),c.push(" mat[0][0] = 1.0;"),c.push(" mat[0][1] = 0.0;"),c.push(" mat[0][2] = 0.0;"),"spherical"===a&&(c.push(" mat[1][0] = 0.0;"),c.push(" mat[1][1] = 1.0;"),c.push(" mat[1][2] = 0.0;")),c.push(" mat[2][0] = 0.0;"),c.push(" mat[2][1] = 0.0;"),c.push(" mat[2][2] =1.0;"),c.push("}"));c.push("void main(void) {"),c.push("vec4 localPosition = vec4(position, 1.0); "),c.push("vec4 worldPosition;"),o&&c.push("localPosition = positionsDecodeMatrix * localPosition;");i.normalsBuf&&(o?c.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):c.push("vec4 localNormal = vec4(normal, 0.0); "),c.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),c.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));c.push("mat4 viewMatrix2 = viewMatrix;"),c.push("mat4 modelMatrix2 = modelMatrix;"),r&&c.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===a||"cylindrical"===a?(c.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),c.push("billboard(modelMatrix2);"),c.push("billboard(viewMatrix2);"),c.push("billboard(modelViewMatrix);"),i.normalsBuf&&(c.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),c.push("billboard(modelNormalMatrix2);"),c.push("billboard(viewNormalMatrix2);"),c.push("billboard(modelViewNormalMatrix);")),c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i.normalsBuf&&c.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(c.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),c.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),c.push("float lambertian = 1.0;"),i.normalsBuf)for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?c.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):c.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}c.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),c.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}c.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),l&&c.push("vWorldPosition = worldPosition;");"points"===i.primitiveName&&c.push("gl_PointSize = pointSize;");c.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(c.push("vFragDepth = 1.0 + clipPos.w;"),c.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return c.push("gl_Position = clipPos;"),c.push("}"),c}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState;e._material._state;const n=e._geometry._state,i=s.sectionPlanes.length>0,a=t.gammaOutput,r=[];r.push("#version 300 es"),r.push("// Lambertian drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(i){r.push("in vec4 vWorldPosition;"),r.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}r.push("in vec4 vColor;"),a&&(r.push("uniform float gammaFactor;"),r.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}"));if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}"points"===n.primitiveName&&(r.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push("float r = dot(cxy, cxy);"),r.push("if (r > 1.0) {"),r.push(" discard;"),r.push("}"));t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");a?r.push("outColor = linearToGamma(vColor, gammaFactor);"):r.push("outColor = vColor;");return r.push("}"),r}(e)):(this.vertex=function(e){const t=e.scene;e._material;const s=e._state,n=t._sectionPlanesState,i=e._geometry._state,a=t._lightsState;let r;const l=s.billboard,o=s.background,c=s.stationary,u=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=ts(e),p=n.sectionPlanes.length>0,A=es(e),d=!!i.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),p&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));a.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===r.type&&"view"===r.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));d&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}u&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&f.push("uniform mat3 uvDecodeMatrix;"));i.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===i.primitiveName&&f.push("uniform float pointSize;");"spherical"!==l&&"cylindrical"!==l||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===l&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),d&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(d?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),c?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):o&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&"world"===r.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===r.type&&("world"===r.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}u&&(d?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));i.colors&&f.push("vColor = color;");"points"===i.primitiveName&&f.push("gl_PointSize = pointSize;");p&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));o&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=e._material,n=e._geometry._state,i=e.scene._sectionPlanesState,a=e.scene._lightsState,r=e._material._state,l=i.sectionPlanes.length>0,o=ts(e),c=n.uvBuf,u="PhongMaterial"===r.type,h="MetallicMaterial"===r.type,p="SpecularMaterial"===r.type,A=es(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));A&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" 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.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(l){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var I=0;I<i.sectionPlanes.length;I++)f.push("uniform bool sectionPlaneActive"+I+";"),f.push("uniform vec3 sectionPlanePos"+I+";"),f.push("uniform vec3 sectionPlaneDir"+I+";")}o&&(a.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),u&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = "+$t[a.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||p)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),a.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+$t[a.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),n.colors&&f.push("in vec4 vColor;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");o&&(a.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));r.ambient&&f.push("uniform vec3 materialAmbient;");r.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==r.alpha&&null!==r.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");r.emissive&&f.push("uniform vec3 materialEmissive;");r.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==r.glossiness&&null!==r.glossiness&&f.push("uniform float materialGlossiness;");void 0!==r.shininess&&null!==r.shininess&&f.push("uniform float materialShininess;");r.specular&&f.push("uniform vec3 materialSpecular;");void 0!==r.metallic&&null!==r.metallic&&f.push("uniform float materialMetallic;");void 0!==r.roughness&&null!==r.roughness&&f.push("uniform float materialRoughness;");void 0!==r.specularF0&&null!==r.specularF0&&f.push("uniform float materialSpecularF0;");c&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));c&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));c&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));c&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));o&&c&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));o&&c&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));o&&c&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));o&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));c&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));c&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));o&&c&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));o&&c&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));o&&c&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));o&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),o)for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(A)for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),l){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(I=0;I<i.sectionPlanes.length;I++)f.push("if (sectionPlaneActive"+I+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+I+".xyz, vWorldPosition.xyz - sectionPlanePos"+I+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===n.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),r.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");r.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):r.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");n.colors&&f.push("diffuseColor *= vColor.rgb;");r.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");r.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==r.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");n.colors&&f.push("alpha *= vColor.a;");void 0!==r.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==r.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==r.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==r.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));c&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+$t[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));c&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+$t[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));c&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+$t[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));c&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+$t[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));c&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));c&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(o&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){c&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),u&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),p&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),u&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||h)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),A&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),u&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}u?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),d&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},$t={};function es(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,s=t.length;e<s;e++)if(t[e].castsShadow)return!0;return!1}function ts(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}$t[3e3]="linearToLinear",$t[3001]="sRGBToLinear";const ss=h.vec3(),ns=new e({}),is=function(e,t){this.id=ns.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Zt(t),this._allocate(t)},as={};is.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let n=as[s];if(!n){if(n=new is(s,e),n.errors)return console.log(n.errors.join("\n")),null;as[s]=n,d.memory.programs++}return n._useCount++,n},is.prototype.put=function(){0==--this._useCount&&(ns.removeItem(this.id),this._program&&this._program.destroy(),delete as[this._hash],d.memory.programs--)},is.prototype.webglContextRestored=function(){this._program=null},is.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=ge.MAX_TEXTURE_UNITS,n=t.scene,i=t._material,a=n.canvas.gl,r=this._program,l=t._state,o=t._material._state,c=t._geometry._state,u=n.camera,h=t.origin,p=l.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,p&&a.depthFunc(a.LEQUAL),this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(l.originHash,h):u.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,u.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,h?k(n.dist,n.dir,h,ss):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(o.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=o.backfaces;e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t);const n=o.frontface;switch(e.frontface!==n&&(n?a.frontFace(a.CCW):a.frontFace(a.CW),e.frontface=n),e.lineWidth!==o.lineWidth&&(a.lineWidth(o.lineWidth),e.lineWidth=o.lineWidth),this._uPointSize&&a.uniform1f(this._uPointSize,o.pointSize),o.type){case"LambertMaterial":this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialColor&&a.uniform4f(this._uMaterialColor,o.color[0],o.color[1],o.color[2],o.alpha),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive);break;case"PhongMaterial":this._uMaterialShininess&&a.uniform1f(this._uMaterialShininess,o.shininess),this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0),i._ambientMap&&i._ambientMap._state.texture&&this._uMaterialAmbientMap&&(r.bindTexture(this._uMaterialAmbientMap,i._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMaterialAmbientMapMatrix&&a.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,i._ambientMap._state.matrix)),i._diffuseMap&&i._diffuseMap._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,i._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,i._diffuseMap._state.matrix)),i._specularMap&&i._specularMap._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,i._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,i._specularMap._state.matrix)),i._emissiveMap&&i._emissiveMap._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,i._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,i._emissiveMap._state.matrix)),i._alphaMap&&i._alphaMap._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,i._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,i._alphaMap._state.matrix)),i._reflectivityMap&&i._reflectivityMap._state.texture&&this._uReflectivityMap&&(r.bindTexture(this._uReflectivityMap,i._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,this._uReflectivityMapMatrix&&a.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,i._reflectivityMap._state.matrix)),i._normalMap&&i._normalMap._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,i._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,i._normalMap._state.matrix)),i._occlusionMap&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,i._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,i._occlusionMap._state.matrix)),i._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&a.uniform1f(this._uDiffuseFresnelEdgeBias,i._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&a.uniform1f(this._uDiffuseFresnelCenterBias,i._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&a.uniform3fv(this._uDiffuseFresnelEdgeColor,i._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&a.uniform3fv(this._uDiffuseFresnelCenterColor,i._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&a.uniform1f(this._uDiffuseFresnelPower,i._diffuseFresnel.power)),i._specularFresnel&&(this._uSpecularFresnelEdgeBias&&a.uniform1f(this._uSpecularFresnelEdgeBias,i._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&a.uniform1f(this._uSpecularFresnelCenterBias,i._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&a.uniform3fv(this._uSpecularFresnelEdgeColor,i._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&a.uniform3fv(this._uSpecularFresnelCenterColor,i._specularFresnel.centerColor),this._uSpecularFresnelPower&&a.uniform1f(this._uSpecularFresnelPower,i._specularFresnel.power)),i._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&a.uniform1f(this._uAlphaFresnelEdgeBias,i._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&a.uniform1f(this._uAlphaFresnelCenterBias,i._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&a.uniform3fv(this._uAlphaFresnelEdgeColor,i._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&a.uniform3fv(this._uAlphaFresnelCenterColor,i._alphaFresnel.centerColor),this._uAlphaFresnelPower&&a.uniform1f(this._uAlphaFresnelPower,i._alphaFresnel.power)),i._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&a.uniform1f(this._uReflectivityFresnelEdgeBias,i._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&a.uniform1f(this._uReflectivityFresnelCenterBias,i._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&a.uniform3fv(this._uReflectivityFresnelEdgeColor,i._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&a.uniform3fv(this._uReflectivityFresnelCenterColor,i._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&a.uniform1f(this._uReflectivityFresnelPower,i._reflectivityFresnel.power)),i._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&a.uniform1f(this._uEmissiveFresnelEdgeBias,i._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&a.uniform1f(this._uEmissiveFresnelCenterBias,i._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&a.uniform3fv(this._uEmissiveFresnelEdgeColor,i._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&a.uniform3fv(this._uEmissiveFresnelCenterColor,i._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&a.uniform1f(this._uEmissiveFresnelPower,i._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&a.uniform3fv(this._uBaseColor,o.baseColor),this._uMaterialMetallic&&a.uniform1f(this._uMaterialMetallic,o.metallic),this._uMaterialRoughness&&a.uniform1f(this._uMaterialRoughness,o.roughness),this._uMaterialSpecularF0&&a.uniform1f(this._uMaterialSpecularF0,o.specularF0),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const t=i._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(r.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uBaseColorMapMatrix&&a.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const n=i._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(r.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicMapMatrix&&a.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const l=i._roughnessMap;l&&l._state.texture&&this._uRoughnessMap&&(r.bindTexture(this._uRoughnessMap,l._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uRoughnessMapMatrix&&a.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,l._state.matrix));const c=i._metallicRoughnessMap;c&&c._state.texture&&this._uMetallicRoughnessMap&&(r.bindTexture(this._uMetallicRoughnessMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&a.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,c._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialGlossiness&&a.uniform1f(this._uMaterialGlossiness,o.glossiness),this._uMaterialReflectivity&&a.uniform1f(this._uMaterialReflectivity,o.reflectivity),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const u=i._diffuseMap;u&&u._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,u._state.matrix));const h=i._specularMap;h&&h._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const p=i._glossinessMap;p&&p._state.texture&&this._uGlossinessMap&&(r.bindTexture(this._uGlossinessMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uGlossinessMapMatrix&&a.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,p._state.matrix));const y=i._specularGlossinessMap;var A,d,f,I;y&&y._state.texture&&this._uSpecularGlossinessMap&&(r.bindTexture(this._uSpecularGlossinessMap,y._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&a.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,y._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix))}this._lastMaterialId=o.id}if(a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),this._uColorize){const e=l.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(a.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}a.uniform3fv(this._uOffset,l.offset),c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(c.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(c.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(c.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(c.flagsBuf),e.bindArray++),c.indicesBuf&&(c.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=c.id),c.indicesBuf?(a.drawElements(c.primitive,c.indicesBuf.numItems,c.indicesBuf.itemType,0),e.drawElements++):c.positions&&(a.drawArrays(a.TRIANGLES,0,c.positions.numItems),e.drawArrays++),p&&a.depthFunc(a.LESS)},is.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=e._material,i=t._lightsState,a=t._sectionPlanesState,r=e._material._state;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const l=this._program;this._uPositionsDecodeMatrix=l.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=l.getLocation("uvDecodeMatrix"),this._uModelMatrix=l.getLocation("modelMatrix"),this._uModelNormalMatrix=l.getLocation("modelNormalMatrix"),this._uViewMatrix=l.getLocation("viewMatrix"),this._uViewNormalMatrix=l.getLocation("viewNormalMatrix"),this._uProjMatrix=l.getLocation("projMatrix"),this._uGammaFactor=l.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=l.getLocation("logDepthBufFC"));const o=i.lights;let c;for(var u=0,h=o.length;u<h;u++){switch(c=o[u],c.type){case"ambient":this._uLightAmbient[u]=l.getLocation("lightAmbient");break;case"dir":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=null,this._uLightDir[u]=l.getLocation("lightDir"+u);break;case"point":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=null,this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u);break;case"spot":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=l.getLocation("lightDir"+u),this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u)}c.castsShadow&&(this._uShadowViewMatrix[u]=l.getLocation("shadowViewMatrix"+u),this._uShadowProjMatrix[u]=l.getLocation("shadowProjMatrix"+u))}i.lightMaps.length>0&&(this._uLightMap="lightMap"),i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(u=0,h=a.sectionPlanes.length;u<h;u++)this._uSectionPlanes.push({active:l.getLocation("sectionPlaneActive"+u),pos:l.getLocation("sectionPlanePos"+u),dir:l.getLocation("sectionPlaneDir"+u)});switch(this._uPointSize=l.getLocation("pointSize"),r.type){case"LambertMaterial":this._uMaterialColor=l.getLocation("materialColor"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=l.getLocation("materialAmbient"),this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=l.getLocation("materialShininess"),n._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=l.getLocation("ambientMapMatrix")),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=l.getLocation("reflectivityMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=l.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=l.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=l.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=l.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=l.getLocation("diffuseFresnelPower")),n._specularFresnel&&(this._uSpecularFresnelEdgeBias=l.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=l.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=l.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=l.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=l.getLocation("specularFresnelPower")),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias=l.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=l.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=l.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=l.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=l.getLocation("alphaFresnelPower")),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=l.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=l.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=l.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=l.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=l.getLocation("reflectivityFresnelPower")),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=l.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=l.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=l.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=l.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=l.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=l.getLocation("materialBaseColor"),this._uMaterialMetallic=l.getLocation("materialMetallic"),this._uMaterialRoughness=l.getLocation("materialRoughness"),this._uMaterialSpecularF0=l.getLocation("materialSpecularF0"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=l.getLocation("baseColorMapMatrix")),n._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=l.getLocation("metallicMapMatrix")),n._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=l.getLocation("roughnessMapMatrix")),n._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=l.getLocation("metallicRoughnessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialGlossiness=l.getLocation("materialGlossiness"),this._uMaterialReflectivity=l.getLocation("reflectivityFresnel"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=l.getLocation("glossinessMapMatrix")),n._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=l.getLocation("materialSpecularGlossinessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"))}this._aPosition=l.getAttribute("position"),this._aNormal=l.getAttribute("normal"),this._aUV=l.getAttribute("uv"),this._aColor=l.getAttribute("color"),this._aFlags=l.getAttribute("flags"),this._uClippable=l.getLocation("clippable"),this._uColorize=l.getLocation("colorize"),this._uOffset=l.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},is.prototype._bindProgram=function(e){const t=ge.MAX_TEXTURE_UNITS,s=this._scene,n=s.canvas.gl,i=s._lightsState,a=s.camera.project;let r;const l=this._program;if(l.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}for(var o=0,c=i.lights.length;o<c;o++)if(r=i.lights[o],this._uLightAmbient[o])n.uniform4f(this._uLightAmbient[o],r.color[0],r.color[1],r.color[2],r.intensity);else if(this._uLightColor[o]&&n.uniform4f(this._uLightColor[o],r.color[0],r.color[1],r.color[2],r.intensity),this._uLightPos[o]&&(n.uniform3fv(this._uLightPos[o],r.pos),this._uLightAttenuation[o]&&n.uniform1f(this._uLightAttenuation[o],r.attenuation)),this._uLightDir[o]&&n.uniform3fv(this._uLightDir[o],r.dir),r.castsShadow){this._uShadowViewMatrix[o]&&n.uniformMatrix4fv(this._uShadowViewMatrix[o],!1,r.getShadowViewMatrix()),this._uShadowProjMatrix[o]&&n.uniformMatrix4fv(this._uShadowProjMatrix[o],!1,r.getShadowProjMatrix());const s=r.getShadowRenderBuf();s&&(l.bindTexture("shadowMap"+o,s.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}i.lightMaps.length>0&&i.lightMaps[0].texture&&this._uLightMap&&(l.bindTexture(this._uLightMap,i.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),i.reflectionMaps.length>0&&i.reflectionMaps[0].texture&&this._uReflectionMap&&(l.bindTexture(this._uReflectionMap,i.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class rs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,n=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),i=t._sectionPlanesState.sectionPlanes.length>0,a=!!e._geometry._state.compressGeometry,r=e._state.billboard,l=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// EmphasisFillShaderSource vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 colorize;"),o.push("uniform vec3 offset;"),a&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");if(o.push("uniform vec4 lightAmbient;"),o.push("uniform vec4 fillColor;"),n){o.push("in vec3 normal;"),o.push("uniform mat4 modelNormalMatrix;"),o.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&o.push("uniform vec3 lightPos"+e+";"))}a&&(o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"))}o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),a&&o.push("localPosition = positionsDecodeMatrix * localPosition;");n&&(a?o.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):o.push("vec4 localNormal = vec4(normal, 0.0); "),o.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),o.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),l&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),n&&(o.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),o.push("billboard(modelNormalMatrix2);"),o.push("billboard(viewNormalMatrix2);"),o.push("billboard(modelViewNormalMatrix);")),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n&&o.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),n)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?o.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}o.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),i&&o.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&o.push("gl_PointSize = pointSize;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}"));t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const ls=new e({}),os=h.vec3(),cs=function(e,t){this.id=ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new rs(t),this._allocate(t)},us={};cs.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=us[t];return s||(s=new cs(t,e),us[t]=s,d.memory.programs++),s._useCount++,s},cs.prototype.put=function(){0==--this._useCount&&(ls.removeItem(this.id),this._program&&this._program.destroy(),delete us[this._hash],d.memory.programs--)},cs.prototype.webglContextRestored=function(){this._program=null},cs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl,r=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,l=t._state,o=t._geometry._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):i.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,c?k(n.dist,n.dir,c,os):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(r.id!==this._lastMaterialId){const t=r.fillColor,s=r.backfaces;e.backfaces!==s&&(s?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=s),a.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(o.normalsBuf),e.bindArray++),o.indicesBuf?(o.indicesBuf.bind(),e.bindArray++):o.positionsBuf,this._lastGeometryId=o.id),o.indicesBuf?(a.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positionsBuf&&(a.drawArrays(a.TRIANGLES,0,o.positionsBuf.numItems),e.drawArrays++)},cs.prototype._allocate=function(e){const t=e.scene,s=t._lightsState,n=t._sectionPlanesState,i=t.canvas.gl;if(this._program=new Be(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=s.lights.length;e<t;e++){switch(s.lights[e].type){case"ambient":this._uLightAmbient[e]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=a.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=a.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=a.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+e),pos:a.getLocation("sectionPlanePos"+e),dir:a.getLocation("sectionPlaneDir"+e)});this._uFillColor=a.getLocation("fillColor"),this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._uClippable=a.getLocation("clippable"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uOffset=a.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},cs.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t._lightsState,i=t.camera,a=i.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];this._uLightAmbient[e]?s.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor)};class hs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Edges drawing vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec4 edgeColor;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));s&&r.push("out vec4 vWorldPosition;");r.push("out vec4 vColor;"),("spherical"===i||"cylindrical"===i)&&(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.push("vColor = edgeColor;"),s&&r.push("vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const ps=new e({}),As=h.vec3(),ds=function(e,t){this.id=ps.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new hs(t),this._allocate(t)},fs={};ds.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=fs[t];return s||(s=new ds(t,e),fs[t]=s,d.memory.programs++),s._useCount++,s},ds.prototype.put=function(){0==--this._useCount&&(ps.removeItem(this.id),this._program&&this._program.destroy(),delete fs[this._hash],d.memory.programs--)},ds.prototype.webglContextRestored=function(){this._program=null},ds.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl;let r;const l=t._state,o=t._geometry,c=o._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(l.originHash,u):i.viewMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,u?k(n.dist,n.dir,u,As):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}switch(s){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;a.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let h;a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?h=o._getEdgeIndices():c.primitive===a.LINES&&(h=c.indicesBuf),h&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,h.numItems,h.itemType,0),e.drawElements++)},ds.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=i.getLocation("edgeColor"),this._aPosition=i.getAttribute("position"),this._uClippable=i.getLocation("clippable"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uOffset=i.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ds.prototype._bindProgram=function(e){const t=this._program,s=this._scene,n=s.canvas.gl,i=s.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor)};class Is{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh picking vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("out vec4 vViewPosition;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==i&&"cylindrical"!==i||(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"));r.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(i.push("uniform vec4 pickColor;"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = pickColor; "),i.push("}"),i}(e)}}const ys=h.vec3(),ms=function(e,t){this._hash=e,this._shaderSource=new Is(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},vs={};ms.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=vs[t];if(!s){if(s=new ms(t,e),s.errors)return console.log(s.errors.join("\n")),null;vs[t]=s,d.memory.programs++}return s._useCount++,s},ms.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete vs[this._hash],d.memory.programs--)},ms.prototype.webglContextRestored=function(){this._program=null},ms.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(i.originHash,l):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?k(s.dist,s.dir,l,ys):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}if(a.id!==this._lastMaterialId){const t=a.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=a.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=a.id}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id);var o=t._state.pickID;const c=o>>24&255,u=o>>16&255,h=o>>8&255,p=255&o;n.uniform4f(this._uPickColor,p/255,h/255,u/255,c/255),n.uniform2fv(this._uPickClipPos,e.pickClipPos),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},ms.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uPickColor=n.getLocation("pickColor"),this._uPickClipPos=n.getLocation("pickClipPos"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},ms.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class ws{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=[];i.push("#version 300 es"),i.push("// Surface picking vertex shader"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform vec3 offset;"),s&&(i.push("uniform bool clippable;"),i.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"));i.push("uniform vec2 pickClipPos;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy -= pickClipPos;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("out vec4 vColor;"),n&&i.push("uniform mat4 positionsDecodeMatrix;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),n&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push(" vec4 worldPosition = modelMatrix * localPosition; "),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&i.push(" vWorldPosition = worldPosition;");i.push(" vColor = color;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Surface picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = vColor;"),i.push("}"),i}(e)}}const gs=h.vec3(),Es=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ws(t),this._allocate(t)},Ts={};Es.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ts[t];if(!s){if(s=new Es(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ts[t]=s,d.memory.programs++}return s._useCount++,s},Es.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ts[this._hash],d.memory.programs--)},Es.prototype.webglContextRestored=function(){this._program=null},Es.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry,l=t._geometry._state,o=t.origin,c=a.backfaces,u=a.frontface,h=s.camera.project,p=r._getPickTrianglePositions(),A=r._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}if(n.uniformMatrix4fv(this._uViewMatrix,!1,o?e.getRTCPickViewMatrix(i.originHash,o):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,o?k(s.dist,s.dir,o,gs):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.logarithmicDepthBufferEnabled&&n.uniform1f(this._uZFar,s.camera.project.far),e.backfaces!==c&&(c?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=c),e.frontface!==u&&(u?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=u),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(p,l.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT)):this._aPosition.bindArrayBuffer(p),n.uniform2fv(this._uPickClipPos,e.pickClipPos),A.bind(),n.enableVertexAttribArray(this._aColor.location),n.vertexAttribPointer(this._aColor.location,A.itemSize,A.itemType,!0,0,0),n.drawArrays(l.primitive,0,p.numItems/3)},Es.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._aColor=n.getAttribute("color"),this._uPickClipPos=n.getLocation("pickClipPos"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))};class bs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push("}"),i}(e)}}const Ds=h.vec3(),Ps=function(e,t){this._hash=e,this._shaderSource=new bs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Rs={};Ps.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Rs[t];if(!s){if(s=new Ps(t,e),s.errors)return console.log(s.errors.join("\n")),null;Rs[t]=s,d.memory.programs++}return s._useCount++,s},Ps.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Rs[this._hash],d.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._material._state,a=t._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=i.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=i.id}const o=s.camera;if(n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCViewMatrix(a.originHash,l):o.viewMatrix),a.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?k(s.dist,s.dir,l,Ds):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),n.uniformMatrix4fv(this._uModelMatrix,n.FALSE,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Ps.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Ps.prototype._bindProgram=function(e){const t=this._scene,s=t.camera.project,n=t.canvas.gl;if(this._program.bind(),e.useProgram++,n.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Cs{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,n=[];n.push("// Mesh shadow vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t&&n.push("out vec4 vWorldPosition;");n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("worldPosition = modelMatrix * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&n.push("vWorldPosition = worldPosition;");return n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("// Mesh shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("vec4 encodeFloat( const in float depth ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(depth * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return i.push("outColor = encodeFloat(gl_FragCoord.z);"),i.push("}"),i}(e)}}const _s=function(e,t){this._hash=e,this._shaderSource=new Cs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Bs={};_s.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let n=Bs[s];if(!n){if(n=new _s(s,e),n.errors)return console.log(n.errors.join("\n")),null;Bs[s]=n,d.memory.programs++}return n._useCount++,n},_s.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Bs[this._hash],d.memory.programs--)},_s.prototype.webglContextRestored=function(){this._program=null},_s.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,n=t._material._state,i=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){const t=n.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=n.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),e.lineWidth!==n.lineWidth&&(s.lineWidth(n.lineWidth),e.lineWidth=n.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,n.pointSize),this._lastMaterialId=n.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),i.combineGeometry){const n=t.vertexBufs;n.id!==this._lastVertexBufsId&&(n.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=n.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),i.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,i.positionsDecodeMatrix),i.combineGeometry?i.indicesBufCombined&&(i.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),i.indicesBuf&&(i.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=i.id),i.combineGeometry?i.indicesBufCombined&&(s.drawElements(i.primitive,i.indicesBufCombined.numItems,i.indicesBufCombined.itemType,0),e.drawElements++):i.indicesBuf?(s.drawElements(i.primitive,i.indicesBuf.numItems,i.indicesBuf.itemType,0),e.drawElements++):i.positions&&(s.drawArrays(s.TRIANGLES,0,i.positions.numItems),e.drawArrays++)},_s.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},_s.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.sectionPlanes.length>0){let e,t,i,a,r;for(let l=0,o=this._uSectionPlanes.length;l<o;l++)e=this._uSectionPlanes[l],t=e.active,i=n.sectionPlanes[l],t&&s.uniform1i(t,i.active),a=e.pos,a&&s.uniform3fv(e.pos,i.pos),r=e.dir,r&&s.uniform3fv(e.dir,i.dir)}};class Os{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Ss=h.OBB3(),Ns=h.vec4(),xs=h.vec4(),Ls=h.vec4(),Ms=h.vec3([1,0,0]),Fs=h.vec3([0,1,0]),Hs=h.vec3([0,0,1]),Us=h.vec3(3),Gs=h.vec3(3),js=h.identityMat4();class Vs extends _{constructor(e,t={}){super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Os,this._state=new Je({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:h.vec3(),origin:null,originHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._worldMatrix=h.identityMat4(),this._worldNormalMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const s=t.origin||t.rtcCenter;if(s&&(this._state.origin=h.vec3(s),this._state.originHash=s.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=h.identityMat4()),this.__localMatrix.set(e||js),h.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=h.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const s=!!e;this.scene._objectColorizeUpdated(this,s),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const s=null!=e;t[3]=s?e:1,this.scene._objectOpacityUpdated(this,s),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=is.get(this),this._emphasisFillRenderer=cs.get(this),this._emphasisEdgesRenderer=ds.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=ms.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=Ps.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=h.mat4()),h.transposeMat4(this._worldMatrix,this._worldNormalMatrix),h.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),s.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){h.transformOBB3(e,this._geometry.obb,Ss),h.OBB3ToAABB3(Ss,t);const s=this._state.offset;if(t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[0],t[4]+=s[1],t[5]+=s[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Ns[0]=e[0],Ns[1]=e[1],Ns[2]=e[2],Ns[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ns,xs),h.mulQuaternions(this.quaternion,xs,Ls),this.quaternion=Ls,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ns[0]=e[0],Ns[1]=e[1],Ns[2]=e[2],Ns[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ns,xs),h.mulQuaternions(xs,this.quaternion,xs),this}rotateX(e){return this.rotate(Ms,e)}rotateY(e){return this.rotate(Fs,e)}rotateZ(e){return this.rotate(Hs,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Us),h.mulVec3Scalar(Us,t,Gs),h.addVec3(this.position,Gs,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ms,e)}translateY(e){return this.translate(Fs,e)}translateZ(e){return this.translate(Hs,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s],n=this.renderFlags;if(t.active)if(this._state.origin){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const i=0===e;n.sectionPlanesActivePerLayer[s]=i}else n.sectionPlanesActivePerLayer[s]=!0;else n.sectionPlanesActivePerLayer[s]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=cs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=cs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=cs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=Ps.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=_s.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=ms.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=Es.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,s){ks(this,e,t,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ks=function(){const e=h.vec3(),t=h.vec3(),s=h.vec3(),n=h.vec3(),i=h.vec3(),a=h.vec3(),r=h.vec4(),l=h.vec3(),o=h.vec3(),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3(),y=h.vec4(),m=h.vec4(),v=h.vec4(),w=h.vec3(),g=h.vec3(),E=h.vec3(),T=h.vec3(),b=h.vec3(),D=h.vec3(),P=h.vec3(),R=h.vec3(),C=h.vec3(),_=h.vec3(),B=h.vec3();return function(O,S,N,x){var L=x.primIndex;if(null!=L&&L>-1){const U=O.geometry._state,j=O.scene,V=j.camera,k=j.canvas;if("triangles"===U.primitiveName){x.primitive="triangle";const j=L,Q=U.indices,W=U.positions;let z,K,Y;if(Q){var M=Q[j+0],F=Q[j+1],H=Q[j+2];a[0]=M,a[1]=F,a[2]=H,x.indices=a,z=3*M,K=3*F,Y=3*H}else z=3*j,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],n[0]=W[K+0],n[1]=W[K+1],n[2]=W[K+2],i[0]=W[Y+0],i[1]=W[Y+1],i[2]=W[Y+2],U.compressGeometry){const e=U.positionsDecodeMatrix;e&&(Bt.decompressPosition(s,e,s),Bt.decompressPosition(n,e,n),Bt.decompressPosition(i,e,i))}x.canvasPos?h.canvasPosToLocalRay(k.canvas,O.origin?G(S,O.origin):S,N,O.worldMatrix,x.canvasPos,e,t):x.origin&&x.direction&&h.worldRayToLocalRay(O.worldMatrix,x.origin,x.direction,e,t),h.normalizeVec3(t),h.rayPlaneIntersect(e,t,s,n,i,r),x.localPos=r,x.position=r,y[0]=r[0],y[1]=r[1],y[2]=r[2],y[3]=1,h.transformVec4(O.worldMatrix,y,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],x.canvasPos&&O.origin&&(l[0]+=O.origin[0],l[1]+=O.origin[1],l[2]+=O.origin[2]),x.worldPos=l,h.transformVec4(V.matrix,m,v),o[0]=v[0],o[1]=v[1],o[2]=v[2],x.viewPos=o,h.cartesianToBarycentric(r,s,n,i,c),x.bary=c;const X=U.normals;if(X){if(U.compressGeometry){const e=3*M,t=3*F,s=3*H;Bt.decompressNormal(X.subarray(e,e+2),u),Bt.decompressNormal(X.subarray(t,t+2),p),Bt.decompressNormal(X.subarray(s,s+2),A)}else u[0]=X[z],u[1]=X[z+1],u[2]=X[z+2],p[0]=X[K],p[1]=X[K+1],p[2]=X[K+2],A[0]=X[Y],A[1]=X[Y+1],A[2]=X[Y+2];const e=h.addVec3(h.addVec3(h.mulVec3Scalar(u,c[0],w),h.mulVec3Scalar(p,c[1],g),E),h.mulVec3Scalar(A,c[2],T),b);x.worldNormal=h.normalizeVec3(h.transformVec3(O.worldNormalMatrix,e,D))}const q=U.uv;if(q){if(d[0]=q[2*M],d[1]=q[2*M+1],f[0]=q[2*F],f[1]=q[2*F+1],I[0]=q[2*H],I[1]=q[2*H+1],U.compressGeometry){const e=U.uvDecodeMatrix;e&&(Bt.decompressUV(d,e,d),Bt.decompressUV(f,e,f),Bt.decompressUV(I,e,I))}x.uv=h.addVec3(h.addVec3(h.mulVec2Scalar(d,c[0],P),h.mulVec2Scalar(f,c[1],R),C),h.mulVec2Scalar(I,c[2],_),B)}}}}}();function Qs(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let n=e.height||1;n<0&&(console.error("negative height not allowed - will invert"),n*=-1);let i=e.radialSegments||32;i<0&&(console.error("negative radialSegments not allowed - will invert"),i*=-1),i<3&&(i=3);let a=e.heightSegments||1;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a<1&&(a=1);const r=!!e.openEnded;let l=e.center;const o=l?l[0]:0,c=l?l[1]:0,u=l?l[2]:0,h=n/2,p=n/a,A=2*Math.PI/i,d=1/i,f=(t-s)/a,I=[],y=[],v=[],w=[];let g,E,T,b,D,P,R,C,_,B,O;const S=(90-180*Math.atan(n/(s-t))/Math.PI)/90;for(g=0;g<=a;g++)for(D=t-g*f,P=h-g*p,E=0;E<=i;E++)T=Math.sin(E*A),b=Math.cos(E*A),y.push(D*T),y.push(S),y.push(D*b),v.push(E*d),v.push(1*g/a),I.push(D*T+o),I.push(P+c),I.push(D*b+u);for(g=0;g<a;g++)for(E=0;E<=i;E++)R=g*(i+1)+E,C=R+i,w.push(R),w.push(C),w.push(C+1),w.push(R),w.push(C+1),w.push(R+1);if(!r&&t>0){for(_=I.length/3,y.push(0),y.push(1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(h+c),I.push(0+u),E=0;E<=i;E++)T=Math.sin(E*A),b=Math.cos(E*A),B=.5*Math.sin(E*A)+.5,O=.5*Math.cos(E*A)+.5,y.push(t*T),y.push(1),y.push(t*b),v.push(B),v.push(O),I.push(t*T+o),I.push(h+c),I.push(t*b+u);for(E=0;E<i;E++)l=_,R=_+1+E,w.push(R),w.push(R+1),w.push(l)}if(!r&&s>0){for(_=I.length/3,y.push(0),y.push(-1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(0-h+c),I.push(0+u),E=0;E<=i;E++)T=Math.sin(E*A),b=Math.cos(E*A),B=.5*Math.sin(E*A)+.5,O=.5*Math.cos(E*A)+.5,y.push(s*T),y.push(-1),y.push(s*b),v.push(B),v.push(O),I.push(s*T+o),I.push(0-h+c),I.push(s*b+u);for(E=0;E<i;E++)l=_,R=_+1+E,w.push(l),w.push(R+1),w.push(R)}return m.apply(e,{positions:I,normals:y,uv:v,indices:w})}function Ws(e={}){const t=e.lod||1,s=e.center?e.center[0]:0,n=e.center?e.center[1]:0,i=e.center?e.center[2]:0;let a=e.radius||1;a<0&&(console.error("negative radius not allowed - will invert"),a*=-1);let r=e.heightSegments||18;r<0&&(console.error("negative heightSegments not allowed - will invert"),r*=-1),r=Math.floor(t*r),r<18&&(r=18);let l=e.widthSegments||18;l<0&&(console.error("negative widthSegments not allowed - will invert"),l*=-1),l=Math.floor(t*l),l<18&&(l=18);const o=[],c=[],u=[],h=[];let p,A,d,f,I,y,v,w,g,E,T,b,D,P,R;for(p=0;p<=r;p++)for(d=p*Math.PI/r,f=Math.sin(d),I=Math.cos(d),A=0;A<=l;A++)y=2*A*Math.PI/l,v=Math.sin(y),w=Math.cos(y),g=w*f,E=I,T=v*f,b=1-A/l,D=p/r,c.push(g),c.push(E),c.push(T),u.push(b),u.push(D),o.push(s+a*g),o.push(n+a*E),o.push(i+a*T);for(p=0;p<r;p++)for(A=0;A<l;A++)P=p*(l+1)+A,R=P+l+1,h.push(P+1),h.push(R+1),h.push(R),h.push(P+1),h.push(R),h.push(P);return m.apply(e,{positions:o,normals:c,uv:u,indices:h})}const zs={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Ks(e={}){var t=e.origin||[0,0,0],s=t[0],n=t[1],i=t[2],a=e.size||1,r=[],l=[],o=e.text;m.isNumeric(o)&&(o=""+o);for(var c,u,h,p,A,d,f,I,y,v=(o||"").split("\n"),w=0,g=0,E=.04,T=0;T<v.length;T++){c=0,h=(u=v[T]).length;for(var b=0;b<h;b++)if(p=zs[u.charAt(b)]){A=1,d=-1,f=-1,I=p.points.length;for(var D=0;D<I;D++)-1!==(y=p.points[D])[0]||-1!==y[1]?(r.push(c+y[0]*a*E+s),r.push(g+y[1]*a*E+n),r.push(0+i),-1===d?d=w:(-1===f||(d=f),f=w),w++,A?A=!1:(l.push(d),l.push(f))):A=1;c+=p.width*E*a}g-=35*E*a}return m.apply(e,{primitive:"lines",positions:r,indices:l})}h.vec3();class Ys extends _{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new Je({active:!0,pos:h.vec3(),dir:h.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const Xs=h.vec4(4),qs=h.vec4(),Js=h.vec4(),Zs=h.vec3([1,0,0]),$s=h.vec3([0,1,0]),en=h.vec3([0,0,1]),tn=h.vec3(3),sn=h.vec3(3),nn=h.identityMat4();class an extends _{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._offset=h.vec3(),this._localMatrix=h.identityMat4(),this._worldMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let s=0,n=e.length;s<n;s++)this.addChild(e[s],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=h.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,s=this._children.length;t<s;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,s=this._children.length;e<s;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,s=this._children.length;t<s;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,s=e._children.length;t<s;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;h.collapseAABB3(this._aabb);for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e.collidable&&h.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+m.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,s=this._children.length;t<s;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+m.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||nn),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return Xs[0]=e[0],Xs[1]=e[1],Xs[2]=e[2],Xs[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Xs,qs),h.mulQuaternions(this.quaternion,qs,Js),this.quaternion=Js,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Xs[0]=e[0],Xs[1]=e[1],Xs[2]=e[2],Xs[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Xs,qs),h.mulQuaternions(qs,this.quaternion,qs),this}rotateX(e){return this.rotate(Zs,e)}rotateY(e){return this.rotate($s,e)}rotateZ(e){return this.rotate(en,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,tn),h.mulVec3Scalar(tn,t,sn),h.addVec3(this.position,sn,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Zs,e)}translateY(e){return this.translate($s,e)}translateZ(e){return this.translate(en,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,n=e.length;s<n;s++)t=e[s],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}class rn extends Lt{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"LambertMaterial",ambient:h.vec3([1,1,1]),color:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const ln={opaque:0,mask:1,blend:2},on=["opaque","mask","blend"];class cn extends Lt{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"MetallicMaterial",baseColor:h.vec4([1,1,1]),emissive:h.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=ln[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return on[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const un={opaque:0,mask:1,blend:2},hn=["opaque","mask","blend"];class pn extends Lt{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"SpecularMaterial",diffuse:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),specular:h.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=un[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return hn[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}function An(e,t,s=null){let n;const i=t;if(1009===i)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(1015===i)return e.FLOAT;if(1016===i)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1023===i)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(1028===i)return e.RED;if(1022===i)return e.RGBA;if(1029===i)return e.RED_INTEGER;if(1030===i)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i)if(3001===s){const t=Ke(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===i)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=Ke(e,"WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===i)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){const t=Ke(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===i)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i){const t=Ke(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===i||37496===i){const t=Ke(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===i)return 3001===s?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){const t=Ke(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===i){const t=Ke(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===i)return 3001===s?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===i?e.UNSIGNED_INT_24_8:1e3===i?e.REPEAT:1001===i?e.CLAMP_TO_EDGE:1004===i||1005===i?e.NEAREST_MIPMAP_LINEAR:1007===i?e.LINEAR_MIPMAP_NEAREST:1008===i?e.LINEAR_MIPMAP_LINEAR:1003===i?e.NEAREST:1006===i?e.LINEAR:null}const dn=new Uint8Array([0,0,0,1]);class fn{constructor({gl:e,target:t,format:s,type:n,wrapS:i,wrapT:a,wrapR:r,encoding:l,preloadColor:o,premultiplyAlpha:c,flipY:u}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!u,this.unpackAlignment=4,this.wrapS=i||1e3,this.wrapT=a||1e3,this.wrapR=r||1e3,this.encoding=l||3001,this.texture=e.createTexture(),o&&this.setPreloadColor(o),this.allocated=!0}setPreloadColor(e){e?(dn[0]=Math.floor(255*e[0]),dn[1]=Math.floor(255*e[1]),dn[2]=Math.floor(255*e[2]),dn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(dn[0]=0,dn[1]=0,dn[2]=0,dn[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let s=0,n=e.length;s<n;s++)t.texImage2D(e[s],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,dn)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,dn);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const s=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let n=!1;s.bindTexture(this.target,this.texture);const i=s.getParameter(s.UNPACK_FLIP_Y_WEBGL);s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY);const a=s.getParameter(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL);s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const r=s.getParameter(s.UNPACK_ALIGNMENT);s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment);const l=s.getParameter(s.UNPACK_COLORSPACE_CONVERSION_WEBGL);s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=An(s,this.minFilter);s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,o),o!==s.NEAREST_MIPMAP_NEAREST&&o!==s.LINEAR_MIPMAP_NEAREST&&o!==s.NEAREST_MIPMAP_LINEAR&&o!==s.LINEAR_MIPMAP_LINEAR||(n=!0);const c=An(s,this.magFilter);c&&s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,c);const u=An(s,this.wrapS);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,u);const h=An(s,this.wrapT);h&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,h);const p=An(s,this.format,this.encoding),A=An(s,this.type),d=In(s,this.internalFormat,p,A,this.encoding,!1);if(this.target===s.TEXTURE_CUBE_MAP){if(m.isArray(e)){const t=e,n=[s.TEXTURE_CUBE_MAP_POSITIVE_X,s.TEXTURE_CUBE_MAP_NEGATIVE_X,s.TEXTURE_CUBE_MAP_POSITIVE_Y,s.TEXTURE_CUBE_MAP_NEGATIVE_Y,s.TEXTURE_CUBE_MAP_POSITIVE_Z,s.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,i=n.length;e<i;e++)s.texImage2D(n[e],0,d,p,A,t[e])}}else s.texImage2D(s.TEXTURE_2D,0,d,p,A,e);n&&s.generateMipmap(this.target),s.bindTexture(this.target,null),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a),s.pixelStorei(s.UNPACK_ALIGNMENT,r),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l)}setCompressedData({mipmaps:e,props:t={}}){const s=this.gl,n=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),s.activeTexture(s.TEXTURE0+0),s.bindTexture(this.target,this.texture);let i=e.length>1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const a=An(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);const r=An(s,this.wrapT);if(r&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,r),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=An(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}i?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,yn(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,yn(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,An(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,An(s,this.magFilter)));const l=An(s,this.format,this.encoding),o=An(s,this.type),c=In(s,this.internalFormat,l,o,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,c,e[0].width,e[0].height);for(let t=0,n=e.length;t<n;t++){const n=e[t];1023!==this.format?null!==l?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,n.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):s.texSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,o,n.data)}s.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const s=An(t,e.minFilter);s&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,s),s!==t.NEAREST_MIPMAP_NEAREST&&s!==t.LINEAR_MIPMAP_NEAREST&&s!==t.NEAREST_MIPMAP_LINEAR&&s!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const s=An(t,e.magFilter);s&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,s))}if(void 0!==e.wrapS){const s=An(t,e.wrapS);s&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,s))}if(void 0!==e.wrapT){const s=An(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function In(e,t,s,n,i,a=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let r=s;return s===e.RED&&(n===e.FLOAT&&(r=e.R32F),n===e.HALF_FLOAT&&(r=e.R16F),n===e.UNSIGNED_BYTE&&(r=e.R8)),s===e.RG&&(n===e.FLOAT&&(r=e.RG32F),n===e.HALF_FLOAT&&(r=e.RG16F),n===e.UNSIGNED_BYTE&&(r=e.RG8)),s===e.RGBA&&(n===e.FLOAT&&(r=e.RGBA32F),n===e.HALF_FLOAT&&(r=e.RGBA16F),n===e.UNSIGNED_BYTE&&(r=3001===i&&!1===a?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT_4_4_4_4&&(r=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(r=e.RGB5_A1)),r!==e.R16F&&r!==e.R32F&&r!==e.RG16F&&r!==e.RG32F&&r!==e.RGBA16F&&r!==e.RGBA32F||Ke(e,"EXT_color_buffer_float"),r}function yn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function mn(e){if(!vn(e.width)||!vn(e.height)){const t=document.createElement("canvas");t.width=wn(e.width),t.height=wn(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function vn(e){return 0==(e&e-1)}function wn(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class gn extends _{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Je({texture:new fn({gl:this.scene.canvas.gl}),matrix:h.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=h.vec2([0,0]),this._scale=h.vec2([1,1]),this._rotate=h.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new fn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=h.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=h.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?h.mulMat4(t,s):s),0!==this._rotate&&(s=h.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?h.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=mn(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=mn(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}const En=d.memory,Tn=h.AABB3();class bn extends Et{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Je({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=h.OBB3();const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var i;if(t.positionsDecodeMatrix);else{const e=Bt.getPositionsBounds(t.positions),a=Bt.compressPositions(t.positions,e.min,e.max);i=a.quantized,s.positionsDecodeMatrix=a.decodeMatrix,s.positionsBuf=new Oe(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),En.positions+=s.positionsBuf.numItems,h.positions3ToAABB3(t.positions,this._aabb),h.positions3ToAABB3(i,Tn,s.positionsDecodeMatrix),h.AABB3ToOBB3(Tn,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new Oe(n,n.ARRAY_BUFFER,e,e.length,4,n.STATIC_DRAW),En.colors+=s.colorsBuf.numItems}if(t.uv){const e=Bt.getUVBounds(t.uv),i=Bt.compressUVs(t.uv,e.min,e.max),a=i.quantized;s.uvDecodeMatrix=i.decodeMatrix,s.uvBuf=new Oe(n,n.ARRAY_BUFFER,a,a.length,2,n.STATIC_DRAW),En.uvs+=s.uvBuf.numItems}if(t.normals){const e=Bt.compressNormals(t.normals);let i=s.compressGeometry;s.normalsBuf=new Oe(n,n.ARRAY_BUFFER,e,e.length,3,n.STATIC_DRAW,i),En.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,e,e.length,1,n.STATIC_DRAW),En.indices+=s.indicesBuf.numItems;const a=Tt(i,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),En.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),En.meshes--}}var Dn={};function Pn(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let s=e.divisions||1;s<0&&(console.error("negative divisions not allowed - will invert"),s*=-1),s<1&&(s=1),t=t||10,s=s||10;const n=t/s,i=t/2,a=[],r=[];let l=0;for(let e=0,t=-i;e<=s;e++,t+=n)a.push(-i),a.push(0),a.push(t),a.push(i),a.push(0),a.push(t),a.push(t),a.push(0),a.push(-i),a.push(t),a.push(0),a.push(i),r.push(l++),r.push(l++),r.push(l++),r.push(l++);return m.apply(e,{primitive:"lines",positions:a,indices:r})}function Rn(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let n=e.xSegments||1;n<0&&(console.error("negative xSegments not allowed - will invert"),n*=-1),n<1&&(n=1);let i=e.xSegments||1;i<0&&(console.error("negative zSegments not allowed - will invert"),i*=-1),i<1&&(i=1);const a=e.center,r=a?a[0]:0,l=a?a[1]:0,o=a?a[2]:0,c=t/2,u=s/2,h=Math.floor(n)||1,p=Math.floor(i)||1,A=h+1,d=p+1,f=t/h,I=s/p,y=new Float32Array(A*d*3),v=new Float32Array(A*d*3),w=new Float32Array(A*d*2);let g,E,T,b,D,P,R,C=0,_=0;for(g=0;g<d;g++){const e=g*I-u;for(E=0;E<A;E++)T=E*f-c,y[C]=T+r,y[C+1]=l,y[C+2]=-e+o,v[C+2]=-1,w[_]=E/h,w[_+1]=(p-g)/p,C+=3,_+=2}C=0;const B=new(y.length/3>65535?Uint32Array:Uint16Array)(h*p*6);for(g=0;g<p;g++)for(E=0;E<h;E++)b=E+A*g,D=E+A*(g+1),P=E+1+A*(g+1),R=E+1+A*g,B[C]=R,B[C+1]=D,B[C+2]=b,B[C+3]=R,B[C+4]=P,B[C+5]=D,C+=6;return m.apply(e,{positions:y,normals:v,uv:w,indices:B})}function Cn(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let s=e.tube||.3;s<0&&(console.error("negative tube not allowed - will invert"),s*=-1);let n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<4&&(n=4);let i=e.tubeSegments||24;i<0&&(console.error("negative tubeSegments not allowed - will invert"),i*=-1),i<4&&(i=4);let a=e.arc||2*Math.PI;a<0&&(console.warn("negative arc not allowed - will invert"),a*=-1),a>360&&(a=360);const r=e.center;let l=r?r[0]:0,o=r?r[1]:0;const c=r?r[2]:0,u=[],p=[],A=[],d=[];let f,I,y,v,w,g,E,T,b,D,P,R;for(T=0;T<=i;T++)for(E=0;E<=n;E++)f=E/n*a,I=.785398+T/i*Math.PI*2,l=t*Math.cos(f),o=t*Math.sin(f),y=(t+s*Math.cos(I))*Math.cos(f),v=(t+s*Math.cos(I))*Math.sin(f),w=s*Math.sin(I),u.push(y+l),u.push(v+o),u.push(w+c),A.push(1-E/n),A.push(T/i),g=h.normalizeVec3(h.subVec3([y,v,w],[l,o,c],[]),[]),p.push(g[0]),p.push(g[1]),p.push(g[2]);for(T=1;T<=i;T++)for(E=1;E<=n;E++)b=(n+1)*T+E-1,D=(n+1)*(T-1)+E-1,P=(n+1)*(T-1)+E,R=(n+1)*T+E,d.push(b),d.push(D),d.push(P),d.push(P),d.push(R),d.push(b);return m.apply(e,{positions:u,normals:p,uv:A,indices:d})}Dn.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Dn.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Dn.parse._buffToStr(e));window.location.href=s},Dn.clone=function(e){return JSON.parse(JSON.stringify(e))},Dn.bin={},Dn.bin.f=new Float32Array(1),Dn.bin.fb=new Uint8Array(Dn.bin.f.buffer),Dn.bin.rf=function(e,t){for(var s=Dn.bin.f,n=Dn.bin.fb,i=0;i<4;i++)n[i]=e[t+i];return s[0]},Dn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Dn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Dn.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Dn.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Dn.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Dn.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Dn.parse={},Dn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",n=0;n<t.length;n++)s=s.concat(String.fromCharCode(t[n]));return s},Dn.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),s=new Uint8Array(t),n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t},Dn.parse._readLine=function(e,t){for(var s="";10!=e[t];)s+=String.fromCharCode(e[t++]);return s},Dn.parse.fromJSON=function(e){return JSON.parse(Dn.parse._buffToStr(e))},Dn.parse.toJSON=function(e){var t=JSON.stringify(e);return Dn.parse._strToBuff(t)},Dn.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},s={from:0,to:0},n=0,i=new Uint8Array(e);n<i.length;){var a=Dn.parse._readLine(i,n);n+=a.length+1;var r=(a=(a=a.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==r[0]&&(s.to=t.i_verts.length,null==t.groups[r[1]]&&(t.groups[r[1]]={from:t.i_verts.length,to:0}),s=t.groups[r[1]]),"v"==r[0]){var l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_verts.push(l,o,c)}if("vt"==r[0]){l=parseFloat(r[1]),o=1-parseFloat(r[2]);t.c_uvt.push(l,o)}if("vn"==r[0]){l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_norms.push(l,o,c)}if("f"==r[0]){var u=r[1].split("/"),h=r[2].split("/"),p=r[3].split("/"),A=parseInt(u[0])-1,d=parseInt(h[0])-1,f=parseInt(p[0])-1,I=parseInt(u[1])-1,y=parseInt(h[1])-1,m=parseInt(p[1])-1,v=parseInt(u[2])-1,w=parseInt(h[2])-1,g=parseInt(p[2])-1,E=t.c_verts.length/3,T=t.c_uvt.length/2,b=t.c_norms.length/3;if(A<0&&(A=E+A+1),d<0&&(d=E+d+1),f<0&&(f=E+f+1),I<0&&(I=T+I+1),y<0&&(y=T+y+1),m<0&&(m=T+m+1),v<0&&(v=b+v+1),w<0&&(w=b+w+1),g<0&&(g=b+g+1),t.i_verts.push(A,d,f),t.i_uvt.push(I,y,m),t.i_norms.push(v,w,g),5==r.length){var D=r[4].split("/"),P=parseInt(D[0])-1,R=parseInt(D[1])-1,C=parseInt(D[2])-1;P<0&&(P=E+P+1),R<0&&(R=T+R+1),C<0&&(C=b+C+1),t.i_verts.push(A,f,P),t.i_uvt.push(I,m,R),t.i_norms.push(v,g,C)}}}return s.to=t.i_verts.length,t},Dn.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},s={};s.ident=Dn.bin.ril(e,0),s.version=Dn.bin.ril(e,4),s.skinwidth=Dn.bin.ril(e,8),s.skinheight=Dn.bin.ril(e,12),s.framesize=Dn.bin.ril(e,16),s.num_skins=Dn.bin.ril(e,20),s.num_vertices=Dn.bin.ril(e,24),s.num_st=Dn.bin.ril(e,28),s.num_tris=Dn.bin.ril(e,32),s.num_glcmds=Dn.bin.ril(e,36),s.num_frames=Dn.bin.ril(e,40),s.offset_skins=Dn.bin.ril(e,44),s.offset_st=Dn.bin.ril(e,48),s.offset_tris=Dn.bin.ril(e,52),s.offset_frames=Dn.bin.ril(e,56),s.offset_glcmds=Dn.bin.ril(e,60),s.offset_end=Dn.bin.ril(e,64);var n=s.offset_st;t.c_uvt=[];for(var i=0;i<s.num_st;i++){var a=Dn.bin.rsl(e,n)/s.skinwidth,r=Dn.bin.rsl(e,n+2)/s.skinheight;t.c_uvt.push(a,r),n+=4}n=s.offset_tris;var l=[],o=[];t.i_verts=l,t.i_uvt=o;for(i=0;i<s.num_tris;i++)l.push(Dn.bin.rsl(e,n),Dn.bin.rsl(e,n+2),Dn.bin.rsl(e,n+4)),o.push(Dn.bin.rsl(e,n+6),Dn.bin.rsl(e,n+8),Dn.bin.rsl(e,n+10)),n+=12;n=s.offset_skins;t.skins=[];for(i=0;i<s.num_skins;i++)t.skins.push(Dn.bin.rASCII0(e,n)),n+=64;n=s.offset_frames;t.frames=[];var c=Dn.parse.fromMD2._normals;for(i=0;i<s.num_frames;i++){var u={},h=Dn.bin.rf(e,n),p=Dn.bin.rf(e,n+4),A=Dn.bin.rf(e,n+8);n+=12;var d=Dn.bin.rf(e,n),f=Dn.bin.rf(e,n+4),I=Dn.bin.rf(e,n+8);n+=12,u.name=Dn.bin.rASCII0(e,n),n+=16,u.verts=[],u.norms=[];for(var y=0;y<s.num_vertices;y++)u.verts.push(e[n]*h+d,e[n+1]*p+f,e[n+2]*A+I),u.norms.push(c[3*e[n+3]],c[3*e[n+3]+1],c[3*e[n+3]+2]),n+=4;t.frames.push(u)}return t},Dn.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Dn.parse.fromCollada=function(e){var t=Dn.parse._buffToStr(e),s=(new DOMParser).parseFromString(t,"text/xml"),n={},i=(s=s.childNodes[0]).getElementsByTagName("asset")[0],a=s.getElementsByTagName("library_geometries")[0],r=s.getElementsByTagName("library_images")[0],l=s.getElementsByTagName("library_materials")[0],o=s.getElementsByTagName("library_effects")[0];return i&&(n.asset=Dn.parse.fromCollada._asset(i)),a&&(n.geometries=Dn.parse.fromCollada._libGeometries(a)),r&&(n.images=Dn.parse.fromCollada._libImages(r)),l&&(n.materials=Dn.parse.fromCollada._libMaterials(l)),o&&(n.effects=Dn.parse.fromCollada._libEffects(o)),n},Dn.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Dn.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],s=0;s<e.length;s++){var n=e[s],i=Dn.parse.fromCollada._getMesh(n.getElementsByTagName("mesh")[0]);t.push(i)}return t},Dn.parse.fromCollada._getMesh=function(e){for(var t={},s=e.getElementsByTagName("source"),n=t.sources={},i=0;i<s.length;i++){for(var a=s[i].getElementsByTagName("float_array")[0].textContent.split(" "),r=a.length-(""==a[a.length-1]?1:0),l=new Array(r),o=0;o<r;o++)l[o]=parseFloat(a[o]);n[s[i].getAttribute("id")]=l}t.triangles=[];var c=e.getElementsByTagName("triangles");if(null==c)return t;for(i=0;i<c.length;i++){var u={},h=c[i];u.material=h.getAttribute("material");var p=h.getElementsByTagName("input"),A=[];for(o=0;o<p.length;o++){var d=p[o];l=[];A[parseInt(d.getAttribute("offset"))]=l;var f=d.getAttribute("semantic");u["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):d.getAttribute("source").substring(1),u["i_"+f]=l,n[u["s_"+f]]}var I=h.getElementsByTagName("p")[0].textContent.split(" "),y=3*Math.floor(I.length/3);for(o=0;o<y;o++)A[o%p.length].push(parseInt(I[o]));t.triangles.push(u)}return t},Dn.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("id")]=e[s].getElementsByTagName("init_from")[0].textContent;return t},Dn.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("name")]=e[s].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Dn.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},s=0;s<e.length;s++){for(var n={},i=e[s].getElementsByTagName("newparam"),a=0;a<i.length;a++){var r=i[a].getElementsByTagName("surface")[0];r&&(n.surface=r.getElementsByTagName("init_from")[0].textContent)}t[e[s].getAttribute("id")]=n}return t},Dn.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Dn.bin.rsl(e,0))return null;for(var s=Dn.bin.ril(e,2),n=6;n<s;){var i=Dn.bin.rsl(e,n),a=Dn.bin.ril(e,n+2);15677==i&&(t.edit=Dn.parse.from3DS._edit3ds(e,n,a)),45056==i&&(t.keyf=Dn.parse.from3DS._keyf3ds(e,n,a)),n+=a}return t},Dn.parse.from3DS._edit3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);16384==a&&(null==n.objects&&(n.objects=[]),n.objects.push(Dn.parse.from3DS._edit_object(e,i,r))),i+=r}return n},Dn.parse.from3DS._keyf3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);45058==a&&(null==n.desc&&(n.desc=[]),n.desc.push(Dn.parse.from3DS._keyf_objdes(e,i,r))),i+=r}return n},Dn.parse.from3DS._keyf_objdes=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);45072==a&&(n.hierarchy=Dn.parse.from3DS._keyf_objhierarch(e,i,r)),45073==a&&(n.dummy_name=Dn.bin.rASCII0(e,i+6)),i+=r}return n},Dn.parse.from3DS._keyf_objhierarch=function(e,t,s){var n={},i=t+6;return n.name=Dn.bin.rASCII0(e,i),i+=n.name.length+1,n.hierarchy=Dn.bin.rsl(e,i+4),n},Dn.parse.from3DS._edit_object=function(e,t,s){var n={},i=t+6;for(n.name=Dn.bin.rASCII0(e,i),i+=n.name.length+1;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);16640==a&&(n.mesh=Dn.parse.from3DS._obj_trimesh(e,i,r)),i+=r}return n},Dn.parse.from3DS._obj_trimesh=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);16656==a&&(n.vertices=Dn.parse.from3DS._tri_vertexl(e,i,r)),16672==a&&(n.indices=Dn.parse.from3DS._tri_facel1(e,i,r)),16704==a&&(n.uvt=Dn.parse.from3DS._tri_mappingcoors(e,i,r)),16736==a&&(n.local=Dn.parse.from3DS._tri_local(e,i,r)),i+=r}return n},Dn.parse.from3DS._tri_vertexl=function(e,t,s){var n=[],i=t+6,a=Dn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Dn.bin.rf(e,i)),n.push(Dn.bin.rf(e,i+4)),n.push(Dn.bin.rf(e,i+8)),i+=12;return n},Dn.parse.from3DS._tri_facel1=function(e,t,s){var n=[],i=t+6,a=Dn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Dn.bin.rsl(e,i)),n.push(Dn.bin.rsl(e,i+2)),n.push(Dn.bin.rsl(e,i+4)),i+=8;return n},Dn.parse.from3DS._tri_mappingcoors=function(e,t,s){var n=[],i=t+6,a=Dn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Dn.bin.rf(e,i)),n.push(1-Dn.bin.rf(e,i+4)),i+=8;return n},Dn.parse.from3DS._tri_local=function(e,t,s){var n={},i=t+6;return n.X=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n.Y=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n.Z=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n.C=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n},Dn.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},s={};return s.id=Dn.bin.ril(e,0),s.verS=Dn.bin.ril(e,4),s.texS=Dn.bin.ril(e,8),s.indS=Dn.bin.ril(e,12),s.verO=Dn.bin.ril(e,16),s.verL=Dn.bin.ril(e,20),s.texO=Dn.bin.ril(e,24),s.texL=Dn.bin.ril(e,28),s.indO=Dn.bin.ril(e,32),s.indL=Dn.bin.ril(e,36),0!=s.verO&&(t.vertices=Dn.parse.fromBIV._readFloats(e,s.verO,s.verL)),0!=s.texO&&(t.uvt=Dn.parse.fromBIV._readFloats(e,s.texO,s.texL)),0!=s.indO&&(t.indices=Dn.parse.fromBIV._readInts(e,s.indO,s.indL,s.indS)),t},Dn.parse.toBIV=function(e){for(var t=0,s=0;s<e.indices.length;s++)t=Math.max(t,e.indices[s]);var n=32;t<=65535&&(n=16);var i=40;e.vertices&&(i+=4*e.vertices.length),e.uvt&&(i+=4*e.uvt.length),e.indices&&(i+=e.indices.length*n/8);var a=new Uint8Array(i);Dn.bin.wil(a,0,1769365870),Dn.bin.wil(a,4,32),Dn.bin.wil(a,8,32),Dn.bin.wil(a,12,n);var r=40;return e.vertices&&(Dn.bin.wil(a,16,r),Dn.bin.wil(a,20,4*e.vertices.length),Dn.parse.fromBIV._writeFloats(a,r,e.vertices),r+=4*e.vertices.length),e.uvt&&(Dn.bin.wil(a,24,r),Dn.bin.wil(a,28,4*e.uvt.length),Dn.parse.fromBIV._writeFloats(a,r,e.uvt),r+=4*e.uvt.length),e.indices&&(Dn.bin.wil(a,32,r),Dn.bin.wil(a,36,4*e.indices.length),Dn.parse.fromBIV._writeInts(a,r,e.indices,n)),a.buffer},Dn.parse.fromBIV._readFloats=function(e,t,s){for(var n=[],i=0;i<s/4;i++)n.push(Dn.bin.rf(e,t+4*i));return n},Dn.parse.fromBIV._writeFloats=function(e,t,s){for(var n=0;n<s.length;n++)Dn.bin.wf(e,t+4*n,s[n])},Dn.parse.fromBIV._readInts=function(e,t,s,n){for(var i=[],a=0;a<s/4;a++)16==n&&i.push(Dn.bin.rsl(e,t+2*a)),32==n&&i.push(Dn.bin.ril(e,t+4*a));return i},Dn.parse.fromBIV._writeInts=function(e,t,s,n){for(var i=0;i<s.length;i++)16==n&&Dn.bin.wsl(e,t+2*i,s[i]),32==n&&Dn.bin.wil(e,t+4*i,s[i])},Dn.gen={},Dn.gen.Plane=function(e,t,s,n){s||(s=1),n||(n=1);for(var i={verts:[],inds:[],uvt:[]},a=e+1,r=t+1,l=0;l<r;l++)for(var o=0;o<a;o++){var c=o*(2/e)-1,u=l*(2/t)-1;i.verts.push(c,u,0),i.uvt.push(s*o/e,n*l/t),l<t&&o<e&&i.inds.push(l*a+o,l*a+o+1,(l+1)*a+o,l*a+o+1,(l+1)*a+o,(l+1)*a+o+1)}return i},Dn.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Dn.gen.Sphere=function(e,t){for(var s={verts:[],inds:[],uvt:[]},n=e+1,i=t+1,a=0;a<i;a++)for(var r=0;r<n;r++){var l=-Math.PI/2+a*Math.PI/t,o=2*r*Math.PI/e,c=Math.cos(l)*Math.cos(o),u=Math.sin(l),h=Math.cos(l)*Math.sin(o);s.verts.push(c,u,h),s.uvt.push(r/e,a/t),a<t&&r<e&&s.inds.push(n*a+r,n*a+r+1,n*(a+1)+r,n*a+r+1,n*(a+1)+r,n*(a+1)+r+1)}return s},Dn.mat={},Dn.mat.scale=function(e,t,s){return[e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1]},Dn.mat.translate=function(e,t,s){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1]},Dn.mat.rotateDeg=function(e,t,s){var n=Math.PI/180;return Dn.mat.rotate(e*n,t*n,s*n)},Dn.mat.rotate=function(e,t,s){var n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i=e,a=t,r=s,l=Math.cos(i),o=Math.cos(a),c=Math.cos(r),u=Math.sin(i),h=Math.sin(a),p=Math.sin(r);return n[0]=o*c,n[1]=-o*p,n[2]=h,n[4]=l*p+u*h*c,n[5]=l*c-u*h*p,n[6]=-u*o,n[8]=u*p-l*h*c,n[9]=u*c+l*h*p,n[10]=l*o,n},Dn.edit={},Dn.edit.interpolate=function(e,t,s,n){for(var i=0;i<e.length;i++)s[i]=e[i]+n*(t[i]-e[i])},Dn.edit.transform=function(e,t){for(var s=0;s<e.length;s+=3){var n=e[s],i=e[s+1],a=e[s+2];e[s+0]=t[0]*n+t[4]*i+t[8]*a+t[12],e[s+1]=t[1]*n+t[5]*i+t[9]*a+t[13],e[s+2]=t[2]*n+t[6]*i+t[10]*a+t[14]}},Dn.edit.unwrap=function(e,t,s){for(var n=new Array(Math.floor(e.length/3)*s),i=0;i<e.length;i++)for(var a=0;a<s;a++)n[i*s+a]=t[e[i]*s+a];return n},Dn.edit.remap=function(e,t,s,n){for(var i=new Array(s.length),a=0;a<e.length;a++)for(var r=0;r<n;r++)i[t[a]*n+r]=s[e[a]*n+r];return i},Dn.utils={},Dn.utils.getAABB=function(e){var t,s,n,i,a,r;i=a=r=-(t=s=n=999999999);for(var l=0;l<e.length;l+=3){var o=e[l+0],c=e[l+1],u=e[l+2];o<t&&(t=o),o>i&&(i=o),c<s&&(s=c),c>a&&(a=c),u<n&&(n=u),c>r&&(r=u)}return{min:{x:t,y:s,z:n},max:{x:i,y:a,z:r}}};class _n extends _{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=h.vec3(t.pos||[0,0,0]),this._up=h.vec3(t.up||[0,1,0]),this._normal=h.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=h.vec3(),this._rtcPos=h.vec3(),this._imageSize=h.vec2(),this._texture=new gn(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new an(this,{matrix:h.inverseMat4(h.lookAtMat4v(this._pos,h.subVec3(this._pos,this._normal,h.mat4()),this._up,h.mat4())),children:[this._bitmapMesh=new Vs(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Nt(this,Rn({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ht(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height*e,1,this._height]}}class Bn extends _{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),n=h.vec3(),i=V(this._positions,new Float32Array(this._positions.length),n,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._mesh=new Vs(this,{visible:t.visible,clippable:t.clippable,collidable:t.collidable,geometry:new bn(this,{primitive:"lines",positions:i?s:this._positions,indices:this._indices,origin:i?n:null}),material:new Ht(this,{diffuse:t.color||[0,0,0],emissive:t.color||[0,0,0]})}),this.scene._lineSetCreated(this)}set visible(e){this._mesh.visible=e}get visible(){return this._mesh.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}const On=h.vec3(),Sn=h.vec3(),Nn=h.vec3(),xn=h.vec3();function Ln(e){return{x:e[0],y:e[1],z:e[2]}}function Mn(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Fn(e){return new Float64Array([e[0],-e[2],e[1]])}function Hn(e){return new Float64Array([e[0],e[2],-e[1]])}const Un=h.vec3(),Gn=(e,t,s,n)=>{var i=e-s,a=t-n;return Math.sqrt(i*i+a*a)};class jn extends _{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._targetMarker=new ie(s,t.target),this._originWorld=h.vec3(),this._targetWorld=h.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthWire=new ae(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisWire=new ae(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisWire=new ae(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisWire=new ae(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthLabel=new le(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisLabel=new le(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisLabel=new le(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisLabel=new le(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var n=this._pp,i=this._cp,a=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var r=a.top-t.top,l=a.left-t.left,o=e.canvas.boundary,c=o[2],u=o[3],p=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,I=s.units,y=s.unitsInfo[I].abbrev;for(var A=0,d=n.length;A<d;A+=4)i[p]=l+Math.floor((1+n[A+0]/n[A+3])*c/2),i[p+1]=r+Math.floor((1-n[A+1]/n[A+3])*u/2),p+=2;if(this._originDot.setPos(i[0],i[1]),this._targetDot.setPos(i[6],i[7]),this._lengthWire.setStartAndEnd(i[0],i[1],i[6],i[7]),this._xAxisWire.setStartAndEnd(i[0],i[1],i[2],i[3]),this._yAxisWire.setStartAndEnd(i[2],i[3],i[4],i[5]),this._zAxisWire.setStartAndEnd(i[4],i[5],i[6],i[7]),this.labelsVisible){this._lengthLabel.setPosOnWire(i[0],i[1],i[6],i[7]),this._xAxisLabel.setPosOnWire(i[0],i[1],i[2],i[3]),this._yAxisLabel.setPosOnWire(i[2],i[3],i[4],i[5]),this._zAxisLabel.setPosOnWire(i[4],i[5],i[6],i[7]);const e=this._approximate?" ~ ":" = ";this._length=Math.abs(h.lenVec3(h.subVec3(this._targetWorld,this._originWorld,Un))),this._lengthLabel.setText(e+(this._length*f).toFixed(2)+y);const t=Math.abs(Gn(i[0],i[1],i[2],i[3])),s=Math.abs(Gn(i[2],i[3],i[4],i[5])),n=Math.abs(Gn(i[4],i[5],i[6],i[7])),a=this.plugin.labelMinAxisLength;this._xAxisLabelCulled=t<a,this._yAxisLabelCulled=s<a,this._zAxisLabelCulled=n<a,this._xAxisLabelCulled?this._xAxisLabel.setCulled(!0):(this._xAxisLabel.setText(e+Math.abs((this._targetWorld[0]-this._originWorld[0])*f).toFixed(2)+y),this._xAxisLabel.setCulled(!this.axisVisible)),this._yAxisLabelCulled?this._yAxisLabel.setCulled(!0):(this._yAxisLabel.setText(e+Math.abs((this._targetWorld[1]-this._originWorld[1])*f).toFixed(2)+y),this._yAxisLabel.setCulled(!this.axisVisible)),this._zAxisLabelCulled?this._zAxisLabel.setCulled(!0):(this._zAxisLabel.setText(e+Math.abs((this._targetWorld[2]-this._originWorld[2])*f).toFixed(2)+y),this._zAxisLabel.setCulled(!this.axisVisible))}else this._lengthLabel.setCulled(!0),this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0);this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._xAxisWire.setVisible(this.axisVisible&&this.xAxisVisible),this._yAxisWire.setVisible(this.axisVisible&&this.yAxisVisible),this._zAxisWire.setVisible(this.axisVisible&&this.zAxisVisible),this._lengthWire.setVisible(this.wireVisible),this._lengthLabel.setCulled(!this.wireVisible),this._cpDirty=!1}}_isSliced(e){const t=this.scene._sectionPlanesState.sectionPlanes;for(let s=0,n=t.length;s<n;s++){const n=t[s];if(h.planeClipsPositions3(n.pos,n.dir,e,4))return!0}return!1}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get target(){return this._targetMarker}get length(){this._update();const e=this.plugin.viewer.scene.metrics.scale;return this._length*e}get color(){return this._color}set color(e){this._color=e,this._originDot.setFillColor(e),this._targetDot.setFillColor(e),this._lengthWire.setColor(e),this._lengthLabel.setFillColor(e)}set visible(e){e=void 0!==e?Boolean(e):this.plugin.defaultVisible,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._lengthWire.setVisible(this._visible&&this._wireVisible),this._lengthLabel.setVisible(this._visible&&this._wireVisible);const t=this._visible&&this._axisVisible&&this._xAxisVisible,s=this._visible&&this._axisVisible&&this._yAxisVisible,n=this._visible&&this._axisVisible&&this._zAxisVisible;this._xAxisWire.setVisible(t),this._yAxisWire.setVisible(s),this._zAxisWire.setVisible(n),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._yAxisLabel.setVisible(s&&!this._yAxisLabelCulled),this._zAxisLabel.setVisible(n&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultOriginVisible,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible)}get originVisible(){return this._originVisible}set targetVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultTargetVisible,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible)}get targetVisible(){return this._targetVisible}set axisEnabled(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisEnabled=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._xAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._xAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisEnabled(){return this._axisEnabled}set axisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisVisible=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._yAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._zAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisVisible(){return this._axisVisible}set xAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._xAxisVisible=e;const t=this._visible&&this._axisVisible&&this._xAxisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get xAxisVisible(){return this._xAxisVisible}set yAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._yAxisVisible=e;const t=this._visible&&this._axisVisible&&this._yAxisVisible&&this._axisEnabled;this._yAxisWire.setVisible(t),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get yAxisVisible(){return this._yAxisVisible}set zAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._zAxisVisible=e;const t=this._visible&&this._axisVisible&&this._zAxisVisible&&this._axisEnabled;this._zAxisWire.setVisible(t),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get zAxisVisible(){return this._zAxisVisible}set wireVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultWireVisible,this._wireVisible=e;var t=this._visible&&this._wireVisible;this._lengthLabel.setVisible(t),this._lengthWire.setVisible(t)}get wireVisible(){return this._wireVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._clickable&&this._axisEnabled),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._clickable&&this._axisEnabled),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._clickable&&this._axisEnabled),this._lengthLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._xAxisWire.setHighlighted(e),this._yAxisWire.setHighlighted(e),this._zAxisWire.setHighlighted(e),this._xAxisLabel.setHighlighted(e),this._yAxisLabel.setHighlighted(e),this._zAxisLabel.setHighlighted(e),this._lengthWire.setHighlighted(e),this._lengthLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._xAxisWire.setClickable(this._clickable),this._yAxisWire.setClickable(this._clickable),this._zAxisWire.setClickable(this._clickable),this._lengthWire.setClickable(this._clickable),this._xAxisLabel.setClickable(this._clickable),this._yAxisLabel.setClickable(this._clickable),this._zAxisLabel.setClickable(this._clickable),this._lengthLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene,t=e.metrics;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onMetricsUnits&&t.off(this._onMetricsUnits),this._onMetricsScale&&t.off(this._onMetricsScale),this._onMetricsOrigin&&t.off(this._onMetricsOrigin),this._onSectionPlaneUpdated&&e.off(this._onSectionPlaneUpdated),this._originDot.destroy(),this._targetDot.destroy(),this._xAxisWire.destroy(),this._yAxisWire.destroy(),this._zAxisWire.destroy(),this._lengthLabel.destroy(),this._xAxisLabel.destroy(),this._yAxisLabel.destroy(),this._zAxisLabel.destroy(),this._lengthWire.destroy(),super.destroy()}}class Vn extends _{get active(){}set snapping(e){}get snapping(){return!0}activate(){}deactivate(){}reset(){}destroy(){}}class kn extends Vn{constructor(e,t={}){super(e.viewer.scene),this.pointerLens=t.pointerLens,this._active=!1;const s=document.createElement("div"),n=this.scene.canvas.canvas;n.parentNode.insertBefore(s,n),s.style.background="black",s.style.border="2px solid blue",s.style.borderRadius="10px",s.style.width="5px",s.style.height="5px",s.style.margin="-200px -200px",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",this._markerDiv=s,this._currentDistanceMeasurement=null,this._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},this._onCameraControlHoverSnapOrSurface=null,this._onCameraControlHoverSnapOrSurfaceOff=null,this._onMouseDown=null,this._onMouseUp=null,this._onCanvasTouchStart=null,this._onCanvasTouchEnd=null,this._snapping=!1!==t.snapping,this._mouseState=0,this._attachPlugin(e,t)}_attachPlugin(e,t={}){this.distanceMeasurementsPlugin=e,this.plugin=e}get active(){return this._active}set snapping(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}get snapping(){return this._snapping}activate(){if(this._active)return;this.fire("activated",!0);const e=this.distanceMeasurementsPlugin,t=this.scene,s=e.viewer.cameraControl,n=t.canvas.canvas;t.input;let i=!1;const a=h.vec3(),r=h.vec2();let l,o;this._mouseState=0,this._onCameraControlHoverSnapOrSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;i=!0,a.set(e.worldPos),r.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=t[0]-5+"px",this._markerDiv.style.marginTop=t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red")):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),n.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=a.slice(),this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),n.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(l=e.clientX,o=e.clientY)}),n.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>l+20||t.clientX<l-20||t.clientY>o+20||t.clientY<o-20||(this._currentDistanceMeasurement?i?(this._currentDistanceMeasurement.clickable=!0,this.distanceMeasurementsPlugin.fire("measurementEnd",this._currentDistanceMeasurement),this._currentDistanceMeasurement=null):(this._currentDistanceMeasurement.destroy(),this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement=null):i&&(this._currentDistanceMeasurement=e.createMeasurement({id:h.createUUID(),origin:{worldPos:a.slice()},target:{worldPos:a.slice()},approximate:!0}),this._currentDistanceMeasurementInitState.axisVisible=this._currentDistanceMeasurement.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurementInitState.xAxisVisible=this._currentDistanceMeasurement.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurementInitState.yAxisVisible=this._currentDistanceMeasurement.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurementInitState.zAxisVisible=this._currentDistanceMeasurement.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurementInitState.wireVisible=this._currentDistanceMeasurement.wireVisible,this._currentDistanceMeasurementInitState.targetVisible=this._currentDistanceMeasurement.targetVisible,this._currentDistanceMeasurement.clickable=!1,this.fire("measurementStart",this._currentDistanceMeasurement))))}),this._onCameraControlHoverSnapOrSurfaceOff=s.on(this._snapping?"hoverSnapOrSurfaceOff":"hoverOff",(e=>{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),i=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),n.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null)}destroy(){this.deactivate(),super.destroy()}}class Qn{constructor(){}getMetaModel(e,t,s){m.loadJSON(e,(e=>{t(e)}),(function(e){s(e)}))}getGLTF(e,t,s){m.loadArraybuffer(e,(e=>{t(e)}),(function(e){s(e)}))}getGLB(e,t,s){m.loadArraybuffer(e,(e=>{t(e)}),(function(e){s(e)}))}getArrayBuffer(e,t,s,n){!function(e,t,s,n){var i=()=>{};s=s||i,n=n||i;const a=/^data:(.*?)(;base64)?,(.*)$/,r=t.match(a);if(r){const e=!!r[2];var l=r[3];l=window.decodeURIComponent(l),e&&(l=window.atob(l));try{const e=new ArrayBuffer(l.length),t=new Uint8Array(e);for(var o=0;o<l.length;o++)t[o]=l.charCodeAt(o);window.setTimeout((function(){s(e)}),0)}catch(e){window.setTimeout((function(){n(e)}),0)}}else{const i=function(e){var t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}(e),a=i+t,r=new XMLHttpRequest;r.open("GET",a,!0),r.responseType="arraybuffer",r.onreadystatechange=function(){4===r.readyState&&(200===r.status?s(r.response):n("loadArrayBuffer error : "+r.response))},r.send(null)}}(e,t,(e=>{s(e)}),(function(e){n(e)}))}}class Wn{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const n=zn(e,s);return n?t?Kn(n,t):n:null}translatePlurals(e,t,s){const n=this._messages[this._locale];if(!n)return null;let i=zn(e,n);return i=0===(t=parseInt(""+t,10))?i.zero:t>1?i.other:i.one,i?(i=Kn(i,[t]),s&&(i=Kn(i,s)),i):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];if(n)for(const e in n)if(n.hasOwnProperty(e)){n[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let n=this._eventSubs[t];n||(n={},this._eventSubs[t]=n);const i=this._eventSubIDMap.addItem();n[i]={callback:s},this._eventSubEvents[i]=t;const a=this._events[t];return void 0!==a&&s(a),i}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function zn(e,t){if(t[e])return t[e];const s=e.split(".");let n=t;for(let e=0,t=s.length;n&&e<t;e++){n=n[s[e]]}return n}function Kn(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,s){return"{{"===e?"{":"}}"===e?"}":t[s]}))}class Yn extends _{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var s=e-t,n=e+t;s<0&&(s=0),n>1&&(n=1);var i=this.getPoint(s),a=this.getPoint(n),r=h.subVec3(a,i,[]);return h.normalizeVec3(r,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,s=[];for(t=0;t<=e;t++)s.push(this.getPoint(t/e));return s}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,s,n=[],i=this.getPoint(0),a=0;for(n.push(0),s=1;s<=e;s++)t=this.getPoint(s/e),a+=h.lenVec3(h.subVec3(t,i,[])),n.push(a),i=t;return this.cacheArcLengths=n,n}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var s,n=this._getLengths(),i=0,a=n.length;s=t||e*n[a-1];for(var r,l=0,o=a-1;l<=o;)if((r=n[i=Math.floor(l+(o-l)/2)]-s)<0)l=i+1;else{if(!(r>0)){o=i;break}o=i-1}if(n[i=o]===s)return i/(a-1);var c=n[i];return(i+(s-c)/(n[i+1]-c))/(a-1)}}class Xn extends Yn{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var s=(t.length-1)*e,n=Math.floor(s),i=s-n,a=t[0===n?n:n-1],r=t[n],l=t[n>t.length-2?t.length-1:n+1],o=t[n>t.length-3?t.length-1:n+2],c=h.vec3();return c[0]=h.catmullRomInterpolate(a[0],r[0],l[0],o[0],i),c[1]=h.catmullRomInterpolate(a[1],r[1],l[1],o[1],i),c[2]=h.catmullRomInterpolate(a[2],r[2],l[2],o[2],i),c}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const qn=h.vec3();const Jn=h.vec3(),Zn=h.vec3(),$n=h.vec3(),ei=h.vec3(),ti=h.vec3();class si extends _{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=h.vec3(),this._eye1=h.vec3(),this._up1=h.vec3(),this._look2=h.vec3(),this._eye2=h.vec3(),this._up2=h.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,s){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=s;const n=this.scene.camera,i=!!e.projection&&e.projection!==n.projection;let a,r,l,o,c;if(this._eye1[0]=n.eye[0],this._eye1[1]=n.eye[1],this._eye1[2]=n.eye[2],this._look1[0]=n.look[0],this._look1[1]=n.look[1],this._look1[2]=n.look[2],this._up1[0]=n.up[0],this._up1[1]=n.up[1],this._up1[2]=n.up[2],this._orthoScale1=n.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)a=e.aabb;else if(6===e.length)a=e;else if(e.eye&&e.look||e.up)r=e.eye,l=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)l=e.look;else{let n=e;if((m.isNumeric(n)||m.isString(n))&&(c=n,n=this.scene.components[c],!n))return this.error("Component not found: "+m.inQuotes(c)),void(t&&(s?t.call(s):t()));i||(a=n.aabb||this.scene.aabb)}const u=e.poi;if(a){if(a[3]<a[0]||a[4]<a[1]||a[5]<a[2])return;if(a[3]===a[0]&&a[4]===a[1]&&a[5]===a[2])return;a=a.slice();const t=h.getAABB3Center(a);this._look2=u||t;const s=h.subVec3(this._eye1,this._look1,Jn),n=h.normalizeVec3(s),i=u?h.getAABB3DiagPoint(a,u):h.getAABB3Diag(a),r=e.fitFOV||this._fitFOV,l=Math.abs(i/Math.tan(r*h.DEGTORAD));this._orthoScale2=1.1*i,this._eye2[0]=this._look2[0]+n[0]*l,this._eye2[1]=this._look2[1]+n[1]*l,this._eye2[2]=this._look2[2]+n[2]*l,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(r||l||o)&&(this._flyingEyeLookUp=!!r&&!!l&&!!o,this._flyingEye=!!r&&!l,this._flyingLook=!!l&&!r,r&&(this._eye2[0]=r[0],this._eye2[1]=r[1],this._eye2[2]=r[2]),l&&(this._look2[0]=l[0],this._look2[1]=l[1],this._look2[2]=l[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));i?("ortho"===e.projection&&"ortho"!==n.projection&&(this._projection2="ortho",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.ortho.matrix.slice(),n.projection="customProjection"),"perspective"===e.projection&&"perspective"!==n.projection&&(this._projection2="perspective",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.perspective.matrix.slice(),n.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,R.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var s,n,i,a,r;if(e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye||e.look||e.up)i=e.eye,a=e.look,r=e.up;else{let t=e;if((m.isNumeric(t)||m.isString(t))&&(n=t,t=this.scene.components[n],!t))return void this.error("Component not found: "+m.inQuotes(n));s=t.aabb||this.scene.aabb}const l=e.poi;if(s){if(s[3]<=s[0]||s[4]<=s[1]||s[5]<=s[2])return;var o=l?h.getAABB3DiagPoint(s,l):h.getAABB3Diag(s);let n;a=l||h.getAABB3Center(s,a),this._trail?h.subVec3(t.look,a,ti):h.subVec3(t.eye,t.look,ti),h.normalizeVec3(ti);n=(void 0!==e.fit?e.fit:this._fit)?Math.abs(o/Math.tan((e.fitFOV||this._fitFOV)*h.DEGTORAD)):h.lenVec3(h.subVec3(t.eye,t.look,Jn)),h.mulVec3Scalar(ti,n),t.eye=h.addVec3(a,ti,Jn),t.look=a,this.scene.camera.ortho.scale=1.1*o}else(i||a||r)&&(i&&(t.eye=i),a&&(t.look=a),r&&(t.up=r));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const s=this.easing?si._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(h.subVec3(n.eye,n.look,ti),n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,$n),n.look=h.subVec3($n,ti,Zn)):this._flyingLook&&(n.look=h.lerpVec3(s,0,1,this._look1,this._look2,Zn),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ei)):this._flyingEyeLookUp&&(n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,$n),n.look=h.lerpVec3(s,0,1,this._look1,this._look2,Zn),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ei)),this._projection2){const t="ortho"===this._projection2?si._easeOutExpo(e,0,1,1):si._easeInCubic(e,0,1,1);n.customProjection.matrix=h.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();R.scheduleTask(this._update,this)}static _ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}static _easeInCubic(e,t,s,n){return s*(e/=n)*e*e+t}static _easeOutExpo(e,t,s,n){return s*(1-Math.pow(2,-10*e/n))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class ni extends _{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new si(this),this._t=0,this.state=ni.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const n=performance.now(),i=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==i)switch(this.state){case ni.SCRUBBING:return;case ni.PLAYING:if(this._t+=this._playingRate*i,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=ni.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case ni.PLAYING_TO:s=this._t+this._playingRate*i*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=ni.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=ni.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=ni.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const n=s.frames[e];n?(this.state=ni.SCRUBBING,this._cameraFlightAnimation.flyTo(n,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=ni.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=ni.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=ni.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}ni.STOPPED=0,ni.SCRUBBING=1,ni.PLAYING=2,ni.PLAYING_TO=3;const ii=h.vec3(),ai=h.vec3();h.vec3();const ri=h.vec3([0,-1,0]),li=h.vec4([0,0,0,1]);function oi(e){if(!ci(e.width)||!ci(e.height)){const t=document.createElement("canvas");t.width=ui(e.width),t.height=ui(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function ci(e){return 0==(e&e-1)}function ui(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class hi extends _{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const s=this.scene.canvas.gl;this._state=new Je({texture:new fn({gl:s,target:s.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),d.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,s=this.scene.canvas.gl;this._images=[];let n=!1,i=0;for(let a=0;a<e.length;a++){const r=new Image;r.onload=function(){let e=r;const l=a;return function(){if(!n&&(e=oi(e),t._images[l]=e,i++,6===i)){let e=t._state.texture;e||(e=new fn({gl:s,target:s.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),r.onerror=function(){n=!0},r.src=e[a]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),d.memory.textures--,this._state.destroy()}}class pi{constructor(e){this._eye=h.vec3(),this._look=h.vec3(),this._up=h.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,s=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:s.fov,fovAxis:s.fovAxis,near:s.near,far:s.far};break;case"ortho":this._projection={projection:"ortho",scale:s.scale,near:s.near,far:s.far};break;case"frustum":this._projection={projection:"frustum",left:s.left,right:s.right,top:s.top,bottom:s.bottom,near:s.near,far:s.far};break;case"custom":this._projection={projection:"custom",matrix:s.matrix.slice()}}}restoreCamera(e,t){const s=e.camera,n=this._projection;function i(){switch(n.type){case"perspective":s.perspective.fov=n.fov,s.perspective.fovAxis=n.fovAxis,s.perspective.near=n.near,s.perspective.far=n.far;break;case"ortho":s.ortho.scale=n.scale,s.ortho.near=n.near,s.ortho.far=n.far;break;case"frustum":s.frustum.left=n.left,s.frustum.right=n.right,s.frustum.top=n.top,s.frustum.bottom=n.bottom,s.frustum.near=n.near,s.frustum.far=n.far;break;case"custom":s.customProjection.matrix=n.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:n.scale,projection:n.projection},(()=>{i(),t()})):(s.eye=this._eye,s.look=this._look,s.up=this._up,i(),s.projection=n.projection)}}const Ai=h.vec3();const di=h.vec3();class fi{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?m.apply(t,{}):null;const s=e.objects,n=!t||t.visible,i=!t||t.edges,a=!t||t.xrayed,r=!t||t.highlighted,l=!t||t.selected,o=!t||t.clippable,c=!t||t.pickable,u=!t||t.colorize,h=!t||t.opacity;for(let e in s)if(s.hasOwnProperty(e)){const t=s[e],p=this.numObjects;if(n&&(this.objectsVisible[p]=t.visible),i&&(this.objectsEdges[p]=t.edges),a&&(this.objectsXrayed[p]=t.xrayed),r&&(this.objectsHighlighted[p]=t.highlighted),l&&(this.objectsSelected[p]=t.selected),o&&(this.objectsClippable[p]=t.clippable),c&&(this.objectsPickable[p]=t.pickable),u){const e=t.colorize;e?(this.objectsColorize[3*p+0]=e[0],this.objectsColorize[3*p+1]=e[1],this.objectsColorize[3*p+2]=e[2],this.objectsHasColorize[p]=!0):this.objectsHasColorize[p]=!1}h&&(this.objectsOpacity[p]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,s=!t||t.visible,n=!t||t.edges,i=!t||t.xrayed,a=!t||t.highlighted,r=!t||t.selected,l=!t||t.clippable,o=!t||t.pickable,c=!t||t.colorize,u=!t||t.opacity;var h=0;const p=e.objects;for(let e in p)if(p.hasOwnProperty(e)){const t=p[e];s&&(t.visible=this.objectsVisible[h]),n&&(t.edges=this.objectsEdges[h]),i&&(t.xrayed=this.objectsXrayed[h]),a&&(t.highlighted=this.objectsHighlighted[h]),r&&(t.selected=this.objectsSelected[h]),l&&(t.clippable=this.objectsClippable[h]),o&&(t.pickable=this.objectsPickable[h]),c&&(this.objectsHasColorize[h]?(di[0]=this.objectsColorize[3*h+0],di[1]=this.objectsColorize[3*h+1],di[2]=this.objectsColorize[3*h+2],t.colorize=di):t.colorize=null),u&&(t.opacity=this.objectsOpacity[h]),h++}}}const Ii=h.OBB3(),yi=h.OBB3();class mi{constructor(e,t,s,n,i,a,r=null,l=0){this.model=e,this.object=null,this.parent=null,this.transform=i,this.textureSet=a,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabb=null,this._abbDirty=!1,this.layer=r,this.portionId=l,this._color=new Uint8Array([s[0],s[1],s[2],n]),this._colorize=new Uint8Array([s[0],s[1],s[2],n]),this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null,this.entity=null,i&&i._addMesh(this)}_sceneModelDirty(){this._aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,n=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),n&&this.layer.setTransparent(this.portionId,t,s)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,n){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,s,n)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabb=e}get aabb(){return this._aabbDirty&&(this.obb&&this.transform&&(h.transformOBB3(this.transform.worldMatrix,this.obb,Ii),h.transformOBB3(this.model.worldMatrix,Ii,yi),h.OBB3ToAABB3(yi,this._aabb)),this._aabbDirty=!1),this._aabb}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const vi=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let wi=0;const gi={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Ei=new Float32Array([1,1,1,1]),Ti=new Float32Array([0,0,0,1]),bi=h.vec4(),Di=h.vec3(),Pi=h.vec3(),Ri=h.mat4();class Ci{constructor(e,t=!1,{instancing:s=!1,edges:n=!1}={}){this._scene=e,this._withSAO=t,this._instancing=s,this._edges=n,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:s}=t.canvas,{model:n,layerIndex:i}=e,a=t._sectionPlanesState.sectionPlanes.length;if(a>0){const r=t._sectionPlanesState.sectionPlanes,l=i*a,o=n.renderFlags;for(let t=0;t<a;t++){const n=this._uSectionPlanes[t];if(n){const i=o.sectionPlanesActivePerLayer[l+t];if(s.uniform1i(n.active,i?1:0),i){const i=r[t],a=e._state.origin;if(a){const e=k(i.dist,i.dir,a,Di);s.uniform3fv(n.pos,e)}else s.uniform3fv(n.pos,i.pos);s.uniform3fv(n.dir,i.dir)}}}}}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uColor||(this._uColor=n.getLocation("silhouetteColor")),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uGammaFactor=n.getLocation("gammaFactor"),t.uniformBlockBinding(n.handle,t.getUniformBlockIndex(n.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=n.getLocation("zFar")),this._uLightAmbient=n.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const i=s.lights;let a;for(let e=0,t=i.length;e<t;e++)switch(a=i[e],a.type){case"dir":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=n.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=n.getLocation("lightDir"+e),this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aMetallicRoughness=n.getAttribute("metallicRoughness"),this._aFlags=n.getAttribute("flags"),this._aPickColor=n.getAttribute("pickColor"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),this._uPickClipPos=n.getLocation("pickClipPos"),this._uDrawingBufferSize=n.getLocation("drawingBufferSize"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrix=n.getAttribute("modelMatrix"),this._aModelMatrixCol0=n.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=n.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=n.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=n.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=n.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=n.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=n.getLocation("intensityRange")),this._uPointSize=n.getLocation("pointSize"),this._uNearPlaneHeight=n.getLocation("nearPlaneHeight")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState,a=i.lights;n.bind(),e.textureUnit=0,this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i.getAmbientColorAndIntensity()),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor);for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}}_makeVAO(e){const t=this._scene.canvas.gl,s=t.createVertexArray();return t.bindVertexArray(s),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer(e.positionsBuf),this._aUV&&this._aUV.bindArrayBuffer(e.uvBuf),this._aNormal&&this._aNormal.bindArrayBuffer(e.normalsBuf),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer(e.colorsBuf),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),s}drawLayer(e,t,s,{colorUniform:n=!1,incrementDrawState:i=!1}={}){const a=ge.MAX_TEXTURE_IMAGE_UNITS,r=this._scene,l=r.canvas.gl,{_state:o,model:c}=t,{textureSet:u,origin:p,positionsDecodeMatrix:A}=o,d=r._lightsState,f=r.pointsMaterial,{camera:I}=c.scene,{viewNormalMatrix:y,project:m}=I,v=e.pickViewMatrix||I.viewMatrix,{position:w,rotationMatrix:g,rotationMatrixConjugate:E,worldNormalMatrix:T}=c;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?l.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(o));let b=0;const D=16;this._matricesUniformBlockBufferData.set(E,0);const P=0!==p[0]||0!==p[1]||0!==p[2],R=0!==w[0]||0!==w[1]||0!==w[2];if(P||R){const e=Di;if(P){const t=h.transformPoint3(g,p,Pi);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=w[0],e[1]+=w[1],e[2]+=w[2],this._matricesUniformBlockBufferData.set(G(v,e,Ri),b+=D)}else this._matricesUniformBlockBufferData.set(v,b+=D);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||m.matrix,b+=D),this._matricesUniformBlockBufferData.set(A,b+=D),this._matricesUniformBlockBufferData.set(T,b+=D),this._matricesUniformBlockBufferData.set(y,b+=D),l.bindBuffer(l.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),l.bufferData(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,l.DYNAMIC_DRAW),l.bindBufferBase(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),l.uniform1i(this._uRenderPass,s),this.setSectionPlanesStateUniforms(t),r.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&l.uniform1f(this._uZFar,r.camera.project.far)}if(this._uPickInvisible&&l.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&l.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&l.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&l.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),this._uUVDecodeMatrix&&l.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._uIntensityRange&&f.filterIntensity&&l.uniform2f(this._uIntensityRange,f.minIntensity,f.maxIntensity),this._uPointSize&&l.uniform1f(this._uPointSize,f.pointSize),this._uNearPlaneHeight){const e="ortho"===r.camera.projection?1:l.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));l.uniform1f(this._uNearPlaneHeight,e)}if(u){const{colorTexture:t,metallicRoughnessTexture:s,emissiveTexture:n,normalsTexture:i,occlusionTexture:r}=u;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uMetallicRoughMap&&s&&(this._program.bindTexture(this._uMetallicRoughMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uEmissiveMap&&n&&(this._program.bindTexture(this._uEmissiveMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uNormalMap&&i&&(this._program.bindTexture(this._uNormalMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uAOMap&&r&&(this._program.bindTexture(this._uAOMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a)}if(d.reflectionMaps.length>0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),this._withSAO){const t=r.sao;if(t.possible){const s=l.drawingBufferWidth,n=l.drawingBufferHeight;bi[0]=s,bi[1]=n,bi[2]=t.blendCutoff,bi[3]=t.blendFactor,l.uniform4fv(this._uSAOParams,bi),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++}}if(n){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===gi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=r.xrayMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===gi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=r.highlightMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===gi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=r.selectedMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else l.uniform4fv(this._uColor,this._edges?Ti:Ei)}this._draw({state:o,frameCtx:e,incrementDrawState:i}),l.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class _i extends Ci{constructor(e,t,{instancing:s=!1,edges:n=!1}={}){super(e,t,{instancing:s,edges:n})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=n.pickElementsCount||s.indicesBuf.numItems,a=n.pickElementsOffset?n.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,a),i&&n.drawElements++}}}class Bi extends _i{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Oi extends Ci{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++)}}class Si extends Oi{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Ni extends Ci{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),i&&n.drawArrays++}}class xi extends Ci{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),i&&n.drawArrays++}}class Li extends Ci{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),i&&n.drawElements++}}class Mi extends Ci{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++}}class Fi extends _i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// Triangles batching draw vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++)i=s.lights[e],"ambient"!==i.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;");for(let e=0,t=s.lights.length;e<t;e++)if(i=s.lights[e],"ambient"!==i.type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class Hi extends _i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),n){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(i),i.push("uniform vec4 lightAmbient;");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];"ambient"!==s.type&&(i.push("uniform vec4 lightColor"+e+";"),"dir"===s.type&&i.push("uniform vec3 lightDir"+e+";"),"point"===s.type&&i.push("uniform vec3 lightPos"+e+";"),"spot"===s.type&&(i.push("uniform vec3 lightPos"+e+";"),i.push("uniform vec3 lightDir"+e+";")))}if(i.push("in vec4 vViewPosition;"),i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}i.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),i.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),i.push("float lambertian = 1.0;"),i.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),i.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),i.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];if("ambient"!==s.type){if("dir"===s.type)"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===s.type)"view"===s.space?i.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):i.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==s.type)continue;"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}i.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),i.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return i.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):i.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Ui extends _i{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching silhouette fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = vColor;"),a.push("}"),a}}class Gi extends Bi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class ji extends Bi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Vi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class ki extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Qi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class Wi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push(" if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class zi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching depth fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("const float packUpScale = 256. / 255.;"),n.push("const float unpackDownscale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),n.push("const float shiftRight8 = 1.0 / 256.;"),n.push("vec4 packDepthToRGBA( const in float v ) {"),n.push(" vec4 r = vec4( fract( v * packFactors ), v );"),n.push(" r.yzw -= r.xyz * shiftRight8;"),n.push(" return r * packUpScale;"),n.push("}"),n.push("in vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}class Ki extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Yi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Xi extends _i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Triangles batching quality draw vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),a.push("vFragDepth = 1.0 + clipPos.w;")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Triangles batching quality draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),r.push("uniform sampler2D uAOMap;"),r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" 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.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),r.push(" return surf_norm;"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("float aoFactor = texture(uAOMap, vUV).r;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class qi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick flat normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class Ji extends _i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,n=e._sectionPlanesState,i=n.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching color texture fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" 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.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),i){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(a),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("in vec4 vViewPosition;"),a.push("in vec4 vColor;"),a.push("in vec2 vUV;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return a.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?a.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):a.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),a.push("float opacity = color.a;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):a.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&a.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Zi{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ui(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Vi(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ki(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Fi(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Fi(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Hi(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Hi(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ji(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ji(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Xi(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Xi(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ui(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new zi(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ki(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Gi(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ji(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Vi(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Qi(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new qi(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ki(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Wi(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Yi(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const $i={};class ea{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const ta=h.mat4(),sa=h.mat4();function na(e,t,s){const n=e.length,i=new Uint16Array(n),a=t[0],r=t[1],l=t[2],o=t[3]-a,c=t[4]-r,u=t[5]-l,p=65525,A=p/o,d=p/c,f=p/u,I=e=>e>=0?e:0;for(let t=0;t<n;t+=3)i[t+0]=Math.floor(I(e[t+0]-a)*A),i[t+1]=Math.floor(I(e[t+1]-r)*d),i[t+2]=Math.floor(I(e[t+2]-l)*f);return h.identityMat4(ta),h.translationMat4v(t,ta),h.identityMat4(sa),h.scalingMat4v([o/p,c/p,u/p],sa),h.mulMat4(ta,sa,s),i}function ia(e,t){const s=e[0],n=e[1],i=e[2],a=e[3]-s,r=e[4]-n,l=e[5]-i,o=65525;return h.identityMat4(ta),h.translationMat4v(e,ta),h.identityMat4(sa),h.scalingMat4v([a/o,r/o,l/o],sa),h.mulMat4(ta,sa,t),t}function aa(e,t,s){let n=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),i=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=n,t=i;e=(1-Math.abs(i))*(n>=0?1:-1),t=(1-Math.abs(n))*(i>=0?1:-1),n=e,i=t}return new Int8Array([Math[t](127.5*n+(n<0?-1:0)),Math[s](127.5*i+(i<0?-1:0))])}function ra(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}const la=h.vec3(),oa=h.vec3(),ca=h.vec3(),ua=h.vec3(),ha=h.mat4();class pa extends Ci{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||a.viewMatrix;this._vaoCache.has(t)?r.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=la;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=oa;if(o){const e=ca;h.transformPoint3(u,o,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,ha),y=ua,y[0]=a.eye[0]-t[0],y[1]=a.eye[1]-t[1],y[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,y),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,f),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(a.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),r.bindBuffer(r.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),r.bufferData(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,r.DYNAMIC_DRAW),r.bindBufferBase(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0),l.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("layout(location = 0) out highp ivec4 outCoords;"),s.push("layout(location = 1) out highp ivec4 outNormal;"),s.push("layout(location = 2) out lowp uvec4 outPickColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Aa=h.vec3(),da=h.vec3(),fa=h.vec3(),Ia=h.vec3(),ya=h.mat4();class ma extends Ci{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||a.viewMatrix;this._vaoCache.has(t)?r.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=Aa;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=da;if(o){const e=fa;h.transformPoint3(u,o,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,ya),y=Ia,y[0]=a.eye[0]-t[0],y[1]=a.eye[1]-t[1],y[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,y),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,f),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(a.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),r.bindBuffer(r.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),r.bufferData(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,r.DYNAMIC_DRAW),r.bindBufferBase(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElements(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0),l.edgeIndicesBuf.unbind()):r.drawArrays(r.POINTS,0,l.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("out highp ivec4 outCoords;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class va{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new pa(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new ma(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new pa(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new ma(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const wa={};const ga=h.mat4(),Ea=h.mat4(),Ta=h.vec4([0,0,0,1]),ba=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]),h.OBB3();const Da=h.vec3(),Pa=h.vec3(),Ra=h.vec3(),Ca=h.vec3(),_a=h.vec3(),Ba=h.vec3(),Oa=h.vec3();class Sa{constructor(e){console.info("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=$i[t];return s||(s=new Zi(e),$i[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete $i[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=wa[t];return s||(s=new va(e),wa[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete wa[t],s._destroy()}))),s}(e.model.scene),this._buffer=new ea(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Je({origin:h.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=h.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=h.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=h.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.normals,i=e.normalsCompressed,a=e.uv,r=e.uvCompressed,l=e.colors,o=e.colorsCompressed,c=e.indices,u=e.edgeIndices,p=e.color,A=e.metallic,d=e.roughness,f=e.opacity,I=e.meshMatrix,y=e.worldAABB,m=e.pickColor,v=this.model.scene,w=this._buffer,g=w.positions.length/3;let E;if(this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";E=s.length/3;for(let e=0,t=s.length;e<t;e++)w.positions.push(s[e]);const e=Bt.getPositionsBounds(s),t=Bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=Bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);y[0]=t[0],y[1]=t[1],y[2]=t[2],y[3]=n[0],y[4]=n[1],y[5]=n[2]}else{if(!t)throw"positions expected";E=t.length/3;const e=t.length,s=w.positions.length;for(let e=0,s=t.length;e<s;e++)w.positions.push(t[e]);if(I)for(let t=s,n=s+e;t<n;t+=3)Ta[0]=w.positions[t+0],Ta[1]=w.positions[t+1],Ta[2]=w.positions[t+2],h.transformPoint4(I,Ta,ba),w.positions[t+0]=ba[0],w.positions[t+1]=ba[1],w.positions[t+2]=ba[2],h.expandAABB3Point3(this._modelAABB,ba),h.expandAABB3Point3(y,ba);else for(let t=s,n=s+e;t<n;t+=3)Ta[0]=w.positions[t+0],Ta[1]=w.positions[t+1],Ta[2]=w.positions[t+2],h.expandAABB3Point3(this._modelAABB,Ta),h.expandAABB3Point3(y,Ta)}if(this._state.origin){const e=this._state.origin;y[0]+=e[0],y[1]+=e[1],y[2]+=e[2],y[3]+=e[0],y[4]+=e[1],y[5]+=e[2]}if(h.expandAABB3(this.aabb,y),i&&i.length>0)for(let e=0,t=i.length;e<t;e++)w.normals.push(i[e]);else if(n&&n.length>0){const e=ga;I?h.inverseMat4(h.transposeMat4(I,Ea),e):h.identityMat4(e,e),function(e,t,s,n,i){function a(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let r,l,o,c,u,p,A=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(p=0;p<s;p+=3)A[0]=t[p],A[1]=t[p+1],A[2]=t[p+2],h.transformVec3(e,A,d),h.normalizeVec3(d,d),o=r=aa(d,"floor","floor"),l=ra(r),c=u=a(d,l),r=aa(d,"ceil","floor"),l=ra(r),c=a(d,l),c>u&&(o=r,u=c),r=aa(d,"floor","ceil"),l=ra(r),c=a(d,l),c>u&&(o=r,u=c),r=aa(d,"ceil","ceil"),l=ra(r),c=a(d,l),c>u&&(o=r,u=c),n[i+p+0]=o[0],n[i+p+1]=o[1],n[i+p+2]=0}(e,n,n.length,w.normals,w.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)w.colors.push(255*l[e]),w.colors.push(255*l[e+1]),w.colors.push(255*l[e+2]),w.colors.push(255);else if(o)for(let e=0,t=l.length;e<t;e+=3)w.colors.push(l[e]),w.colors.push(l[e+1]),w.colors.push(l[e+2]),w.colors.push(255);else if(p){const e=p[0],t=p[1],s=p[2],n=f;for(let i=0;i<E;i++)w.colors.push(e),w.colors.push(t),w.colors.push(s),w.colors.push(n)}const T=null!=A?A:0,b=null!=d?d:255;for(let e=0;e<E;e++)w.metallicRoughness.push(T),w.metallicRoughness.push(b);if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)w.uv.push(a[e]);else if(r&&r.length>0)for(let e=0,t=r.length;e<t;e++)w.uv.push(r[e]);for(let e=0,t=c.length;e<t;e++)w.indices.push(g+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)w.edgeIndices.push(g+u[e]);{const e=w.pickColors.length;for(let t=e,s=e+4*E;t<s;t+=4)w.pickColors.push(m[0]),w.pickColors.push(m[1]),w.pickColors.push(m[2]),w.pickColors.push(m[3])}if(v.entityOffsetsEnabled)for(let e=0;e<E;e++)w.offsets.push(0),w.offsets.push(0),w.offsets.push(0);const D=this._portions.length,P={vertsBaseIndex:g,numVerts:E,indicesBaseIndex:w.indices.length-c.length,numIndices:c.length};return v.pickSurfacePrecisionEnabled&&(P.indices=c,v.entityOffsetsEnabled&&(P.offset=new Float32Array(3))),this._portions.push(P),this._numPortions++,this.model.numPortions++,this._numVerts+=P.numVerts,D}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0){const n=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):na(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=h.mat4());if(e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],s=3*t.vertsBaseIndex,i=s+3*t.numVerts;t.quantizedPositions=n.slice(s,i)}}if(s.normals.length>0){const n=new Int8Array(s.normals);let i=!0;e.normalsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.normals.length,3,t.STATIC_DRAW,i)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.uv.length>0)if(e.uvDecodeMatrix){let n=!1;e.uvBuf=new Oe(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,n)}else{const n=Bt.getUVBounds(s.uv),i=Bt.compressUVs(s.uv,n.min,n.max),a=i.quantized;let r=!1;e.uvDecodeMatrix=h.mat3(i.decodeMatrix),e.uvBuf=new Oe(t,t.ARRAY_BUFFER,a,a.length,2,t.STATIC_DRAW,r)}if(s.metallicRoughness.length>0){const n=new Uint8Array(s.metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Oe(t,t.ARRAY_BUFFER,n,s.metallicRoughness.length,2,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n),a=!1;e.flagsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const n=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,n,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,n=this._portions[s],i=4*n.vertsBaseIndex,a=4*n.numVerts,r=this._scratchMemory.getUInt8Array(a),l=t[0],o=t[1],c=t[2],u=t[3];for(let e=0;e<a;e+=4)r[e+0]=l,r[e+1]=o,r[e+2]=c,r[e+3]=u;this._state.colorsBuf&&this._state.colorsBuf.setData(r,i,a)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=e,a=this._portions[i],r=a.vertsBaseIndex,l=a.numVerts,o=!!(t&Q),c=!!(t&X),u=!!(t&q),h=!!(t&J),p=!!(t&Z),A=!!(t&z),d=!!(t&W);let f,I;f=!o||d||c||u&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,I=!o||d?gi.NOT_RENDERED:h?gi.SILHOUETTE_SELECTED:u?gi.SILHOUETTE_HIGHLIGHTED:c?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let y=0;y=!o||d?gi.NOT_RENDERED:h?gi.EDGES_SELECTED:u?gi.EDGES_HIGHLIGHTED:c?gi.EDGES_XRAYED:p?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let m=o&&!d&&A?gi.PICK:gi.NOT_RENDERED;const v=t&K?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=r,t=r+l;e<t;e++){let t=0;t|=f,t|=I<<4,t|=y<<8,t|=m<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(l);for(let t=0;t<l;t++){let s=0;s|=f,s|=I<<4,s|=y<<8,s|=m<<12,s|=v<<16,e[t]=s}this._state.flagsBuf.setData(e,r,l)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=e,n=this._portions[s],i=3*n.vertsBaseIndex,a=3*n.numVerts,r=this._scratchMemory.getFloat32Array(a),l=t[0],o=t[1],c=t[2];for(let e=0;e<a;e+=3)r[e+0]=l,r[e+1]=o,r[e+2]=c;this._state.offsetsBuf&&this._state.offsetsBuf.setData(r,i,a),this.model.scene.pickSurfacePrecisionEnabled&&(n.offset[0]=t[0],n.offset[1]=t[1],n.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return;const s=this._state,n=this._portions[e];if(!n)return void this.model.error("portion not found: "+e);const i=n.quantizedPositions,a=s.origin,r=n.offset,l=a[0]+r[0],o=a[1]+r[1],c=a[2]+r[2],u=Ta;for(let e=0,n=i.length;e<n;e+=3)u[0]=i[e],u[1]=i[e+1],u[2]=i[e+2],u[3]=1,h.decompressPosition(u,s.positionsDecodeMatrix),h.transformPoint4(this.model.worldMatrix,u),u[0]+=l,u[1]+=o,u[2]+=c,t(u)}getElementsCountAndOffset(e){let t=null,s=null;const n=this._portions[e];return n&&(t=n.numIndices,s=n.indicesBaseIndex),{count:t,offset:s}}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRendererWithSAO&&this._batchingRenderers.pbrRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRendererWithSAO&&this._batchingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._batchingRenderers.flatColorRendererWithSAO&&this._batchingRenderers.flatColorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsFlatRenderer&&this._batchingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,gi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthBufInitRenderer&&this._snapBatchingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,gi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthRenderer&&this._snapBatchingRenderers.snapDepthRenderer.drawLayer(t,this,gi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state,r=this._portions[e];if(!r)return this.model.error("portion not found: "+e),!1;const l=r.quantizedPositions,o=r.indices,c=a.origin,u=r.offset,p=Da,A=Pa;p.set(c?h.subVec3(t,c,Ra):t),A.set(s),u&&h.subVec3(p,u),h.transformRay(this.model.worldNormalMatrix,p,A,p,A);const d=Ca,f=_a,I=Ba;let y=!1,m=0;const v=Oa;for(let e=0,s=o.length;e<s;e+=3){const s=3*o[e],r=3*o[e+1],w=3*o[e+2];if(d[0]=l[s],d[1]=l[s+1],d[2]=l[s+2],f[0]=l[r],f[1]=l[r+1],f[2]=l[r+2],I[0]=l[w],I[1]=l[w+1],I[2]=l[w+2],h.decompressPosition(d,a.positionsDecodeMatrix),h.decompressPosition(f,a.positionsDecodeMatrix),h.decompressPosition(I,a.positionsDecodeMatrix),h.rayTriangleIntersect(p,A,d,f,I,v)){h.transformPoint3(this.model.worldMatrix,v,v),u&&h.addVec3(v,u),c&&h.addVec3(v,c);const e=Math.abs(h.lenVec3(h.subVec3(v,t,[])));(!y||e>m)&&(m=e,n.set(v),i&&h.triangleNormal(d,f,I,i),y=!0)}}return y&&i&&(h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),y}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Na extends Oi{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i,a,r;const l=[];for(l.push("#version 300 es"),l.push("// Instancing geometry drawing vertex shader"),l.push("uniform int renderPass;"),l.push("in vec3 position;"),l.push("in vec2 normal;"),l.push("in vec4 color;"),l.push("in float flags;"),e.entityOffsetsEnabled&&l.push("in vec3 offset;"),l.push("in vec4 modelMatrixCol0;"),l.push("in vec4 modelMatrixCol1;"),l.push("in vec4 modelMatrixCol2;"),l.push("in vec4 modelNormalMatrixCol0;"),l.push("in vec4 modelNormalMatrixCol1;"),l.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(l,!0),e.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;")),l.push("uniform vec4 lightAmbient;"),i=0,a=s.lights.length;i<a;i++)r=s.lights[i],"ambient"!==r.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===r.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===r.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===r.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")));for(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"),n&&(l.push("out vec4 vWorldPosition;"),l.push("out float vFlags;")),l.push("out vec4 vColor;"),l.push("void main(void) {"),l.push("int colorFlag = int(flags) & 0xF;"),l.push("if (colorFlag != renderPass) {"),l.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),l.push("} else {"),l.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),l.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix * worldPosition; "),l.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),l.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),l.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),i=0,a=s.lights.length;i<a;i++)if(r=s.lights[i],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}return l.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),l.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),l.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(l.push("vWorldPosition = worldPosition;"),l.push("vFlags = flags;")),l.push("gl_Position = clipPos;"),l.push("}"),l.push("}"),l}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class xa extends Oi{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let n,i;const a=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry flat-shading drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),a){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];"ambient"!==e.type&&(r.push("uniform vec4 lightColor"+n+";"),"dir"===e.type&&r.push("uniform vec3 lightDir"+n+";"),"point"===e.type&&r.push("uniform vec3 lightPos"+n+";"),"spot"===e.type&&(r.push("uniform vec3 lightPos"+n+";"),r.push("uniform vec3 lightDir"+n+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),a){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}for(r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?r.push("viewLightDir = -normalize(lightPos"+n+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+n+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+n+".rgb * lightColor"+n+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class La extends Oi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing fill fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Ma extends Si{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Fa extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Ha extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class Ua extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Ga extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class ja extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Va extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry depth drawing fragment shader"),a.push("precision highp float;"),a.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec2 vHighPrecisionZW;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),a.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),a.push("}"),a}}class ka extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Qa extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}const Wa={3e3:"linearToLinear",3001:"sRGBToLinear"};class za extends Oi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Instancing geometry quality drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push(" worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),a.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Instancing geometry quality drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" 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.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),r.push(" return normalize(surf_norm );"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = "+Wa[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = "+Wa[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Ka extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class Ya extends Oi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState;let i,a;const r=s.sectionPlanes.length>0,l=[];if(l.push("#version 300 es"),l.push("// Instancing geometry drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),e.logarithmicDepthBufferEnabled&&(l.push("in float isPerspective;"),l.push("uniform float logDepthBufFC;"),l.push("in float vFragDepth;")),l.push("uniform sampler2D uColorMap;"),this._withSAO&&(l.push("uniform sampler2D uOcclusionTexture;"),l.push("uniform vec4 uSAOParams;"),l.push("const float packUpscale = 256. / 255.;"),l.push("const float unpackDownScale = 255. / 256.;"),l.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),l.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),l.push("float unpackRGBToFloat( const in vec4 v ) {"),l.push(" return dot( v, unPackFactors );"),l.push("}")),l.push("uniform float gammaFactor;"),l.push("vec4 linearToLinear( in vec4 value ) {"),l.push(" return value;"),l.push("}"),l.push("vec4 sRGBToLinear( in vec4 value ) {"),l.push(" 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.w );"),l.push("}"),l.push("vec4 gammaToLinear( in vec4 value) {"),l.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),l.push("}"),t&&(l.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),r){l.push("in vec4 vWorldPosition;"),l.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("uniform bool sectionPlaneActive"+e+";"),l.push("uniform vec3 sectionPlanePos"+e+";"),l.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(l),l.push("uniform vec4 lightAmbient;"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];"ambient"!==e.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===e.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===e.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===e.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")))}if(l.push("in vec4 vViewPosition;"),l.push("in vec4 vColor;"),l.push("in vec2 vUV;"),l.push("out vec4 outColor;"),l.push("void main(void) {"),r){l.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),l.push(" if (clippable) {"),l.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("if (sectionPlaneActive"+e+") {"),l.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),l.push("}");l.push(" if (dist > 0.0) { "),l.push(" discard;"),l.push(" }"),l.push("}")}for(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),l.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),l.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),l.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}}return l.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?l.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):l.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),l.push("float opacity = color.a;"),this._withSAO?(l.push(" float viewportWidth = uSAOParams[0];"),l.push(" float viewportHeight = uSAOParams[1];"),l.push(" float blendCutoff = uSAOParams[2];"),l.push(" float blendFactor = uSAOParams[3];"),l.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),l.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb * ambient, opacity);")):l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb, opacity);"),t&&l.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&l.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),l.push("}"),l}}class Xa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new La(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Ha(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ua(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Na(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Na(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new xa(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new xa(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new za(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new za(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ya(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ya(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new La(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Va(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ka(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Ma(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Fa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ha(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ga(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ka(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ua(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ja(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Qa(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const qa={};const Ja=h.vec3(),Za=h.vec3(),$a=h.vec3(),er=h.vec3(),tr=h.mat4();class sr extends Ci{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.canvas.gl,r=i.camera,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||r.viewMatrix;this._vaoCache.has(t)?a.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=Ja;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=Za;if(o){const e=h.transformPoint3(u,o,$a);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,tr),y=er,y[0]=r.eye[0]-t[0],y[1]=r.eye[1]-t[1],y[2]=r.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=r.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;a.uniform3fv(this._uCameraEyeRtc,y),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,f),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(r.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),a.bindBuffer(a.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),a.bufferData(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,a.DYNAMIC_DRAW),a.bindBufferBase(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(l.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(l.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(l.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(l.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1)),l.indicesBuf.bind(),a.drawElementsInstanced(a.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0,l.numInstances),l.indicesBuf.unbind(),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("layout(location = 0) out highp ivec4 outCoords;"),s.push("layout(location = 1) out highp ivec4 outNormal;"),s.push("layout(location = 2) out lowp uvec4 outPickColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const nr=h.vec3(),ir=h.vec3(),ar=h.vec3(),rr=h.vec3(),lr=h.mat4();class or extends Ci{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||a.viewMatrix;this._vaoCache.has(t)?r.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=nr;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=ir;if(o){const e=h.transformPoint3(u,o,ar);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,lr),y=rr,y[0]=a.eye[0]-t[0],y[1]=a.eye[1]-t[1],y[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,y),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,f),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(a.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),r.bindBuffer(r.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),r.bufferData(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,r.DYNAMIC_DRAW),r.bindBufferBase(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(l.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(l.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(l.modelMatrixCol2Buf),r.vertexAttribDivisor(this._aModelMatrixCol0.location,1),r.vertexAttribDivisor(this._aModelMatrixCol1.location,1),r.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(l.flagsBuf),r.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElementsInstanced(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0,l.numInstances),l.edgeIndicesBuf.unbind()):r.drawArraysInstanced(r.POINTS,0,l.positionsBuf.numItems,l.numInstances),r.vertexAttribDivisor(this._aModelMatrixCol0.location,0),r.vertexAttribDivisor(this._aModelMatrixCol1.location,0),r.vertexAttribDivisor(this._aModelMatrixCol2.location,0),r.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&r.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("out highp ivec4 outCoords;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class cr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sr(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new or(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new or(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const ur={};const hr=new Uint8Array(4),pr=new Float32Array(1),Ar=h.vec4([0,0,0,1]),dr=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]);const fr=new Float32Array(3),Ir=h.vec3(),yr=h.vec3(),mr=h.vec3(),vr=h.vec3(),wr=h.vec3(),gr=h.vec3(),Er=h.vec3(),Tr=new Float32Array(4);class br{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=qa[t];return s||(s=new Xa(e),qa[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete qa[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=ur[t];return s||(s=new cr(e),ur[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete ur[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Je({numInstances:0,obb:h.OBB3(),origin:h.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=h.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,n=e.roughness,i=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,a=e.meshMatrix,r=e.aabb,l=e.pickColor;if(this._finalized)throw"Already finalized";const o=t[0],c=t[1],u=t[2];if(this._colors.push(o),this._colors.push(c),this._colors.push(u),this._colors.push(i),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(a[0]),this._modelMatrixCol0.push(a[4]),this._modelMatrixCol0.push(a[8]),this._modelMatrixCol0.push(a[12]),this._modelMatrixCol1.push(a[1]),this._modelMatrixCol1.push(a[5]),this._modelMatrixCol1.push(a[9]),this._modelMatrixCol1.push(a[13]),this._modelMatrixCol2.push(a[2]),this._modelMatrixCol2.push(a[6]),this._modelMatrixCol2.push(a[10]),this._modelMatrixCol2.push(a[14]),this._state.geometry.normals){let e=h.transposeMat4(a,h.mat4()),t=h.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(l[0]),this._pickColors.push(l[1]),this._pickColors.push(l[2]),this._pickColors.push(l[3]);const p=this._state.geometry.positionsCompressed.length,A=this._state.geometry.positionsCompressed,d=this._state.geometry.positionsDecodeMatrix;for(let e=0;e<p;e+=3)Ar[0]=A[e+0],Ar[1]=A[e+1],Ar[2]=A[e+2],h.transformPoint4(d,Ar,dr),h.transformPoint4(a,dr,Ar),h.expandAABB3Point3(r,Ar);if(this._state.origin){const e=this._state.origin;r[0]+=e[0],r[1]+=e[1],r[2]+=e[2],r[3]+=e[0],r[4]+=e[1],r[5]+=e[2]}h.expandAABB3(this.aabb,r),this._state.numInstances++;const f=this._portions.length,I={};return this.model.scene.pickSurfacePrecisionEnabled&&(I.matrix=a.slice(),I.inverseMatrix=null,I.normalMatrix=null),this._portions.push(I),this._numPortions++,this.model.numPortions++,f}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,s=e.textureSet,n=this.model.scene.canvas.gl,i=this._colors.length,a=i/4;if(i>0){let t=!1;e.colorsBuf=new Oe(n,n.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,n.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new Oe(n,n.ARRAY_BUFFER,t,this._metallicRoughness.length,2,n.STATIC_DRAW,s)}if(a>0){let t=!1;e.flagsBuf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(a),a,1,n.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,n.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new Oe(n,n.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,n.STATIC_DRAW,s),e.positionsDecodeMatrix=h.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),i=!1;e.colorsBuf=new Oe(n,n.ARRAY_BUFFER,s,s.length,4,n.STATIC_DRAW,i)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Oe(n,n.ARRAY_BUFFER,s,s.length,2,n.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,n.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,n.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Oe(n,n.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,n.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";hr[0]=t[0],hr[1]=t[1],hr[2]=t[2],hr[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(hr,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&Q),i=!!(t&X),a=!!(t&q),r=!!(t&J),l=!!(t&Z),o=!!(t&z),c=!!(t&W);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,h=!n||c?gi.NOT_RENDERED:r?gi.SILHOUETTE_SELECTED:a?gi.SILHOUETTE_HIGHLIGHTED:i?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let p=0;p=!n||c?gi.NOT_RENDERED:r?gi.EDGES_SELECTED:a?gi.EDGES_HIGHLIGHTED:i?gi.EDGES_XRAYED:l?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?gi.PICK:gi.NOT_RENDERED)<<12,A|=(t&K?1:0)<<16,pr[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(pr,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(fr[0]=t[0],fr[1]=t[1],fr[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(fr,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,n=s.geometry,i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const a=n.quantizedPositions,r=s.origin,l=i.offset,o=r[0]+l[0],c=r[1]+l[1],u=r[2]+l[2],p=Ar,A=i.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=a.length;e<s;e+=3)p[0]=a[e],p[1]=a[e+1],p[2]=a[e+2],h.decompressPosition(p,f),h.transformPoint3(A,p),h.transformPoint3(d,p),p[0]+=o,p[1]+=c,p[2]+=u,t(p)}setMatrix(e,t){if(!this._finalized)throw"Not finalized";var s=4*e;Tr[0]=t[0],Tr[1]=t[4],Tr[2]=t[8],Tr[3]=t[12],this._state.modelMatrixCol0Buf.setData(Tr,s),Tr[0]=t[1],Tr[1]=t[5],Tr[2]=t[9],Tr[3]=t[13],this._state.modelMatrixCol1Buf.setData(Tr,s),Tr[0]=t[2],Tr[1]=t[6],Tr[2]=t[10],Tr[3]=t[14],this._state.modelMatrixCol2Buf.setData(Tr,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRendererWithSAO&&this._instancingRenderers.pbrRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRendererWithSAO&&this._instancingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._instancingRenderers.flatColorRendererWithSAO&&this._instancingRenderers.flatColorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsFlatRenderer&&this._instancingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,gi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthBufInitRenderer&&this._snapInstancingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,gi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthRenderer&&this._snapInstancingRenderers.snapDepthRenderer.drawLayer(t,this,gi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state.geometry,r=this._state,l=this._portions[e];if(!l)return this.model.error("portion not found: "+e),!1;l.inverseMatrix||(l.inverseMatrix=h.inverseMat4(l.matrix,h.mat4())),i&&!l.normalMatrix&&(l.normalMatrix=h.transposeMat4(l.inverseMatrix,h.mat4()));const o=a.quantizedPositions,c=a.indices,u=r.origin,p=l.offset,A=Ir,d=yr;A.set(u?h.subVec3(t,u,mr):t),d.set(s),p&&h.subVec3(A,p),h.transformRay(this.model.worldNormalMatrix,A,d,A,d),h.transformRay(l.inverseMatrix,A,d,A,d);const f=vr,I=wr,y=gr;let m=!1,v=0;const w=Er;for(let e=0,s=c.length;e<s;e+=3){const s=3*c[e+0],a=3*c[e+1],g=3*c[e+2];f[0]=o[s],f[1]=o[s+1],f[2]=o[s+2],I[0]=o[a],I[1]=o[a+1],I[2]=o[a+2],y[0]=o[g],y[1]=o[g+1],y[2]=o[g+2];const{positionsDecodeMatrix:E}=r.geometry;if(h.decompressPosition(f,E),h.decompressPosition(I,E),h.decompressPosition(y,E),h.rayTriangleIntersect(A,d,f,I,y,w)){h.transformPoint3(l.matrix,w,w),h.transformPoint3(this.model.worldMatrix,w,w),p&&h.addVec3(w,p),u&&h.addVec3(w,u);const e=Math.abs(h.lenVec3(h.subVec3(w,t,[])));(!m||e>v)&&(v=e,n.set(w),i&&h.triangleNormal(f,I,y,i),m=!0)}}return m&&i&&(h.transformVec3(l.normalMatrix,i,i),h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),m}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Dr extends Li{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Pr extends Li{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Rr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Dr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Cr={};class _r{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const Br=h.vec4([0,0,0,1]),Or=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]),h.OBB3();class Sr{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Cr[t];return s||(s=new Rr(e),Cr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Cr[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new _r(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Je({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.indices,i=e.color,a=e.opacity,r=e.meshMatrix,l=e.worldAABB;e.pickColor;const o=this._buffer,c=o.positions.length/3;let u;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";u=s.length/3;for(let e=0,t=s.length;e<t;e++)o.positions.push(s[e]);const e=Bt.getPositionsBounds(s),t=Bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=Bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);l[0]=t[0],l[1]=t[1],l[2]=t[2],l[3]=n[0],l[4]=n[1],l[5]=n[2]}else{if(!t)throw"positions expected";u=t.length/3;const e=t.length,s=o.positions.length;for(let e=0,s=t.length;e<s;e++)o.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)Br[0]=o.positions[t+0],Br[1]=o.positions[t+1],Br[2]=o.positions[t+2],h.transformPoint4(r,Br,Or),o.positions[t+0]=Or[0],o.positions[t+1]=Or[1],o.positions[t+2]=Or[2],h.expandAABB3Point3(this._modelAABB,Or),h.expandAABB3Point3(l,Or);else for(let t=s,n=s+e;t<n;t+=3)Br[0]=o.positions[t+0],Br[1]=o.positions[t+1],Br[2]=o.positions[t+2],h.expandAABB3Point3(this._modelAABB,Br),h.expandAABB3Point3(l,Br)}if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}if(h.expandAABB3(this.aabb,l),i){const e=i[0],t=i[1],s=i[2],n=a;for(let i=0;i<u;i++)o.colors.push(e),o.colors.push(t),o.colors.push(s),o.colors.push(n)}if(n)for(let e=0,t=n.length;e<t;e++)o.indices.push(n[e]+c);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<u;e++)o.offsets.push(0),o.offsets.push(0),o.offsets.push(0);const p=this._portions.length/2;return this._portions.push(c),this._portions.push(u),this._numPortions++,this.model.numPortions++,this._numVerts+=u,p}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=na(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.colors.length>0){const n=s.colors.length/4,i=new Float32Array(n);let a=!1;e.flagsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2],c=t[3];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o,a[e+3]=c;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=2*e,a=this._portions[i],r=this._portions[i+1],l=!!(t&Q),o=!!(t&X),c=!!(t&q),u=!!(t&J),h=!!(t&z),p=!!(t&W);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,d=!l||p?gi.NOT_RENDERED:u?gi.SILHOUETTE_SELECTED:c?gi.SILHOUETTE_HIGHLIGHTED:o?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let f=l&&!p&&h?gi.PICK:gi.NOT_RENDERED;const I=t&K?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=a,t=a+r;e<t;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(r);for(let t=0;t<r;t++){let s=0;s|=A,s|=d<<4,s|=f<<12,s|=I<<16,e[t]=s}this._state.flagsBuf.setData(e,a,r)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class Nr extends Mi{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Lines instancing color fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class xr extends Mi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Lr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Nr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Mr={};const Fr=new Uint8Array(4),Hr=new Float32Array(1),Ur=h.vec4([0,0,0,1]),Gr=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]);const jr=new Float32Array(3),Vr=new Float32Array(4);class kr{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=Mr[t];return s||(s=new Lr(e),Mr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Mr[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Je({obb:h.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=h.vec3(e.origin)),this._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,n=e.meshMatrix,i=e.aabb;if(this._finalized)throw"Already finalized";const a=t[0],r=t[1],l=t[2];t[3],this._colors.push(a),this._colors.push(r),this._colors.push(l),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),h.collapseAABB3(i);const o=this._state.obb,c=o.length;for(let e=0;e<c;e+=4)Ur[0]=o[e+0],Ur[1]=o[e+1],Ur[2]=o[e+2],h.transformPoint4(n,Ur,Gr),h.expandAABB3Point3(i,Gr);if(this._state.origin){const e=this._state.origin;i[0]+=e[0],i[1]+=e[1],i[2]+=e[2],i[3]+=e[0],i[4]+=e[1],i[5]+=e[2]}h.expandAABB3(this.aabb,i),this._state.numInstances++;const u=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,u}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,s=t/4;if(t>0){let t=!1;this._state.colorsBuf=new Oe(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fr[0]=t[0],Fr[1]=t[1],Fr[2]=t[2],Fr[3]=t[3],this._state.colorsBuf.setData(Fr,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&Q),i=!!(t&X),a=!!(t&q),r=!!(t&J),l=!!(t&Z),o=!!(t&z),c=!!(t&W);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,h=!n||c?gi.NOT_RENDERED:r?gi.SILHOUETTE_SELECTED:a?gi.SILHOUETTE_HIGHLIGHTED:i?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let p=0;p=!n||c?gi.NOT_RENDERED:r?gi.EDGES_SELECTED:a?gi.EDGES_HIGHLIGHTED:i?gi.EDGES_XRAYED:l?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?gi.PICK:gi.NOT_RENDERED)<<12,A|=(t&K?255:0)<<16,Hr[0]=A,this._state.flagsBuf.setData(Hr,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(jr[0]=t[0],jr[1]=t[1],jr[2]=t[2],this._state.offsetsBuf.setData(jr,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;Vr[0]=t[0],Vr[1]=t[4],Vr[2]=t[8],Vr[3]=t[12],this._state.modelMatrixCol0Buf.setData(Vr,s),Vr[0]=t[1],Vr[1]=t[5],Vr[2]=t[9],Vr[3]=t[13],this._state.modelMatrixCol1Buf.setData(Vr,s),Vr[0]=t[2],Vr[1]=t[6],Vr[2]=t[10],Vr[3]=t[14],this._state.modelMatrixCol2Buf.setData(Vr,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Qr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,n=[];return n.push("#version 300 es"),n.push("// Points batching color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Wr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform vec4 color;"),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points batching silhouette vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("uniform vec4 color;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = color;"),a.push("}"),a}}class zr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class Kr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batched pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batched pick depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Yr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push(" gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching occlusion fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Xr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Qr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Wr(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new zr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Kr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Yr(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const qr={};class Jr{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const Zr=h.vec4(),$r=h.vec4(),el=h.vec4([0,0,0,1]),tl=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]),h.OBB3();class sl{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=qr[t];return s||(s=new Xr(e),qr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete qr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Jr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Je({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.color,i=e.colorsCompressed,a=e.colors,r=e.meshMatrix,l=e.worldAABB,o=e.pickColor,c=this._buffer,u=c.positions.length/3;let p;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e<t;e++)c.positions.push(s[e]);const e=Bt.getPositionsBounds(s),t=Bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,Zr),n=Bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,$r);l[0]=t[0],l[1]=t[1],l[2]=t[2],l[3]=n[0],l[4]=n[1],l[5]=n[2],p=s.length/3}else{if(!t)throw"positions expected";p=t.length/3;const e=t.length,s=c.positions.length;for(let e=0,s=t.length;e<s;e++)c.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)el[0]=c.positions[t+0],el[1]=c.positions[t+1],el[2]=c.positions[t+2],h.transformPoint4(r,el,tl),c.positions[t+0]=tl[0],c.positions[t+1]=tl[1],c.positions[t+2]=tl[2],h.expandAABB3Point3(this._modelAABB,tl),h.expandAABB3Point3(l,tl);else for(let t=s,n=s+e;t<n;t+=3)el[0]=c.positions[t+0],el[1]=c.positions[t+1],el[2]=c.positions[t+2],h.expandAABB3Point3(this._modelAABB,el),h.expandAABB3Point3(l,el)}if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}if(h.expandAABB3(this.aabb,l),i)for(let e=0,t=i.length;e<t;e++)c.colors.push(i[e]);else if(a)for(let e=0,t=a.length;e<t;e++)c.colors.push(255*a[e]);else if(n){const e=n[0],t=n[1],s=n[2],i=1;for(let n=0;n<p;n++)c.colors.push(e),c.colors.push(t),c.colors.push(s),c.colors.push(i)}{const e=c.pickColors.length;for(let t=e,s=e+4*p;t<s;t+=4)c.pickColors.push(o[0]),c.pickColors.push(o[1]),c.pickColors.push(o[2]),c.pickColors.push(o[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<p;e++)c.offsets.push(0),c.offsets.push(0),c.offsets.push(0);const A=this._portions.length/2;return this._portions.push(u),this._portions.push(p),this._numPortions++,this.model.numPortions++,A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=na(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n);let a=!1;e.flagsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=2*e,i=this._portions[n],a=this._portions[n+1],r=this._scratchMemory.getFloat32Array(a),l=!!(t&Q),o=!!(t&X),c=!!(t&q),u=!!(t&J),h=!!(t&z),p=!!(t&W);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,d=!l||p?gi.NOT_RENDERED:u?gi.SILHOUETTE_SELECTED:c?gi.SILHOUETTE_HIGHLIGHTED:o?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let f=l&&!p&&h?gi.PICK:gi.NOT_RENDERED;const I=t&K?1:0;for(let e=0;e<a;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,r[e]=t}this._state.flagsBuf.setData(r,i)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class nl extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class il extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 color;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),n.push("uniform vec4 silhouetteColor;"),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class al extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick mesh fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class rl extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push(" vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class ll extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 color;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class ol extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points instancing depth vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("const float packUpScale = 256. / 255.;"),a.push("const float unpackDownscale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),a.push("const float shiftRight8 = 1.0 / 256.;"),a.push("vec4 packDepthToRGBA( const in float v ) {"),a.push(" vec4 r = vec4( fract( v * packFactors ), v );"),a.push(" r.yzw -= r.xyz * shiftRight8;"),a.push(" return r * packUpScale;"),a.push("}"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return a.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class cl extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class ul{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new il(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ol(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new al(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new rl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ll(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new cl(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const hl={};const pl=new Uint8Array(4),Al=new Float32Array(1),dl=h.vec4([0,0,0,1]),fl=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]);const Il=new Float32Array(3),yl=new Float32Array(4);class ml{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=hl[t];return s||(s=new ul(e),hl[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete hl[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Je({obb:h.OBB3(),numInstances:0,origin:e.origin?h.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.aabb,n=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(n[0]),this._pickColors.push(n[1]),this._pickColors.push(n[2]),this._pickColors.push(n[3]),h.collapseAABB3(s);const i=this._state.obb,a=i.length;for(let e=0;e<a;e+=4)dl[0]=i[e+0],dl[1]=i[e+1],dl[2]=i[e+2],h.transformPoint4(t,dl,fl),h.expandAABB3Point3(s,fl);if(this._state.origin){const e=this._state.origin;s[0]+=e[0],s[1]+=e[1],s[2]+=e[2],s[3]+=e[0],s[4]+=e[1],s[5]+=e[2]}h.expandAABB3(this.aabb,s),this._state.numInstances++;const r=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,r}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4,s=this._state,n=s.geometry;if(t>0){let n=!1;s.flagsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,n)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(n.positionsCompressed&&n.positionsCompressed.length>0){const t=!1;s.positionsBuf=new Oe(e,e.ARRAY_BUFFER,n.positionsCompressed,n.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=h.mat4(n.positionsDecodeMatrix)}if(n.colorsCompressed&&n.colorsCompressed.length>0){const t=new Uint8Array(n.colorsCompressed),i=!1;s.colorsBuf=new Oe(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,i)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;s.pickColorsBuf=new Oe(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";pl[0]=t[0],pl[1]=t[1],pl[2]=t[2],this._state.colorsBuf.setData(pl,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&Q),i=!!(t&X),a=!!(t&q),r=!!(t&J),l=!!(t&Z),o=!!(t&z),c=!!(t&W);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,h=!n||c?gi.NOT_RENDERED:r?gi.SILHOUETTE_SELECTED:a?gi.SILHOUETTE_HIGHLIGHTED:i?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let p=0;p=!n||c?gi.NOT_RENDERED:r?gi.EDGES_SELECTED:a?gi.EDGES_HIGHLIGHTED:i?gi.EDGES_XRAYED:l?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?gi.PICK:gi.NOT_RENDERED)<<12,A|=(t&K?255:0)<<16,Al[0]=A,this._state.flagsBuf.setData(Al,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Il[0]=t[0],Il[1]=t[1],Il[2]=t[2],this._state.offsetsBuf.setData(Il,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;yl[0]=t[0],yl[1]=t[4],yl[2]=t[8],yl[3]=t[12],this._state.modelMatrixCol0Buf.setData(yl,s),yl[0]=t[1],yl[1]=t[5],yl[2]=t[9],yl[3]=t[13],this._state.modelMatrixCol1Buf.setData(yl,s),yl[0]=t[2],yl[1]=t[6],yl[2]=t[10],yl[3]=t[14],this._state.modelMatrixCol2Buf.setData(yl,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class vl{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class wl{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const gl={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class El{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t<s;t+=2){const s=this.handlers[t],n=this.handlers[t+1];if(s.global&&(s.lastIndex=0),s.test(e))return n}return null}}const Tl=new El;class bl{constructor(e){this.manager=void 0!==e?e:Tl,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const s=this;return new Promise((function(n,i){s.load(e,n,t,i)}))}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}}const Dl={};class Pl extends bl{constructor(e){super(e)}load(e,t,s,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=gl.get(e);if(void 0!==i)return this.manager.itemStart(e),setTimeout((()=>{t&&t(i),this.manager.itemEnd(e)}),0),i;if(void 0!==Dl[e])return void Dl[e].push({onLoad:t,onProgress:s,onError:n});Dl[e]=[],Dl[e].push({onLoad:t,onProgress:s,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),r=this.mimeType,l=this.responseType;fetch(a).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const s=Dl[e],n=t.body.getReader(),i=t.headers.get("Content-Length"),a=i?parseInt(i):0,r=0!==a;let l=0;const o=new ReadableStream({start(e){!function t(){n.read().then((({done:n,value:i})=>{if(n)e.close();else{l+=i.byteLength;const n=new ProgressEvent("progress",{lengthComputable:r,loaded:l,total:a});for(let e=0,t=s.length;e<t;e++){const t=s[e];t.onProgress&&t.onProgress(n)}e.enqueue(i),t()}}))}()}});return new Response(o)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r)));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),s=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(s);return e.arrayBuffer().then((e=>n.decode(e)))}}})).then((t=>{gl.add(e,t);const s=Dl[e];delete Dl[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const s=Dl[e];if(void 0===s)throw this.manager.itemError(e),t;delete Dl[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onError&&n.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Rl{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 s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:t,msg:s,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(s,n)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((s=>{const n=this._getIdleWorker();-1!==n?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=s,this.workers[n].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Cl=0;class _l{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Rl,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const n=e.capabilities;this._workerConfig={astcSupported:n.astcSupported,etc1Supported:n.etc1Supported,etc2Supported:n.etc2Supported,dxtSupported:n.dxtSupported,bptcSupported:n.bptcSupported,pvrtcSupported:n.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Pl;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new Pl;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,n]).then((([e,t])=>{const s=_l.BasisWorker.toString(),n=["/* constants */","let _EngineFormat = "+JSON.stringify(_l.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(_l.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(_l.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([n])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),Cl>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Cl++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((n,i)=>{const a=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:a},e))).then((e=>{const s=e.data,{mipmaps:a,width:r,height:l,format:o,type:c,error:u,dfdTransferFn:h,dfdFlags:p}=s;if("error"===c)return i(u);t.setCompressedData({mipmaps:a,props:{format:o,minFilter:1===a.length?1006:1008,magFilter:1===a.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&p)}}),n()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Cl--}}_l.BasisFormat={ETC1S:0,UASTC_4x4:1},_l.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},_l.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},_l.BasisWorker=function(){let e,t,s;const n=_EngineFormat,i=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const u=r.data;switch(u.type){case"init":e=u.config,h=u.transcoderBinary,t=new Promise((e=>{s={wasmBinary:h,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f}=function(t){const r=new s.KTX2File(new Uint8Array(t));function u(){r.close(),r.delete()}if(!r.isValid())throw u(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=r.isUASTC()?a.UASTC_4x4:a.ETC1S,p=r.getWidth(),A=r.getHeight(),d=r.getLevels(),f=r.getHasAlpha(),I=r.getDFDTransferFunc(),y=r.getDFDFlags(),{transcoderFormat:m,engineFormat:v}=function(t,s,r,u){let h,p;const A=t===a.ETC1S?l:o;for(let n=0;n<A.length;n++){const i=A[n];if(e[i.if]&&(i.basisFormat.includes(t)&&!(u&&i.transcoderFormat.length<2)&&(!i.needsPowerOfTwo||c(s)&&c(r))))return h=i.transcoderFormat[u?1:0],p=i.engineFormat[u?1:0],{transcoderFormat:h,engineFormat:p}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=i.RGBA32,p=n.RGBAFormat,{transcoderFormat:h,engineFormat:p}}(h,p,A,f);if(!p||!A||!d)throw u(),new Error("KTX2TextureTranscoder: Invalid texture");if(!r.startTranscoding())throw u(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const w=[];for(let e=0;e<d;e++){const t=r.getImageLevelInfo(e,0,0),s=t.origWidth,n=t.origHeight,i=new Uint8Array(r.getImageTranscodedSizeInBytes(e,0,0,m));if(!r.transcodeImage(i,e,0,0,m,0,-1,-1))throw u(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");w.push({data:i,width:s,height:n})}return u(),{width:p,height:A,hasAlpha:f,mipmaps:w,format:v,dfdTransferFn:I,dfdFlags:y}}(u.buffers[0]),I=[];for(let e=0;e<p.length;++e)I.push(p[e].data.buffer);self.postMessage({type:"transcode",id:u.id,width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f},I)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:u.id,error:e.message})}}))}var h}));const r=[{if:"astcSupported",basisFormat:[a.UASTC_4x4],transcoderFormat:[i.ASTC_4x4,i.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC7_M5,i.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC1,i.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1,i.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.PVRTC1_4_RGB,i.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],l=r.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),o=r.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function c(e){return e<=2||0==(e&e-1)&&0!==e}};const Bl={};function Ol(e){const t=e.scene.id;let s=Bl[t];return s||(s=new _l({viewer:e}),Bl[t]=s,e.scene.on("destroyed",(()=>{delete Bl[t],s.destroy()}))),s}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class s{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class n{constructor(){this.items=[]}}class i{constructor(e,t,s,n,i){this.id=e,this.getTitle=t,this.doAction=s,this.getEnabled=n,this.getShown=i,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let a=!0,r=a?Float64Array:Float32Array;const l=new r(3),o=new r(16),c=new r(16),u=new r(4),h={setDoublePrecisionEnabled(e){a=e,r=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const s=t.indexOf("#");return s===e.length&&t.startsWith(e)?t.substring(s+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new r(e||2),vec3:e=>new r(e||3),vec4:e=>new r(e||4),mat3:e=>new r(e||9),mat3ToMat4:(e,t=new r(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new r(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,s){const n=new r(2);for(let i=0,a=e.length;i<a;i++)h.splitDouble(e[i],n),t[i]=n[0],s[i]=n[1]},splitDouble(e,t){const s=r.from([e])[0],n=e-s;t[0]=s,t[1]=n},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&s]}${e[s>>8&255]}-${e[s>>16&15|64]}${e[s>>24&255]}-${e[63&n|128]}${e[n>>8&255]}-${e[n>>16&255]}${e[n>>24&255]}${e[255&i]}${e[i>>8&255]}${e[i>>16&255]}${e[i>>24&255]}`}})(),clamp:(e,t,s)=>Math.max(t,Math.min(s,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s),addVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s),addVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s),addVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s),subVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s),subVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s),subVec2:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s),geometricMeanVec2(...e){const t=new r(e[0]);for(let s=1;s<e.length;s++)t[0]+=e[s][0],t[1]+=e[s][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s),subScalarVec4:(e,t,s)=>(s||(s=e),s[0]=t-e[0],s[1]=t-e[1],s[2]=t-e[2],s[3]=t-e[3],s),mulVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]*t[0],s[1]=e[1]*t[1],s[2]=e[2]*t[2],s[3]=e[3]*t[3],s),mulVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s),mulVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s),mulVec2Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s),divVec3:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s),divVec4:(e,t,s)=>(s||(s=e),s[0]=e[0]/t[0],s[1]=e[1]/t[1],s[2]=e[2]/t[2],s[3]=e[3]/t[3],s),divScalarVec3:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s),divVec3Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s),divVec4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]/t,s[1]=e[1]/t,s[2]=e[2]/t,s[3]=e[3]/t,s),divScalarVec4:(e,t,s)=>(s||(s=t),s[0]=e/t[0],s[1]=e/t[1],s[2]=e/t[2],s[3]=e/t[3],s),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const s=e[0],n=e[1],i=e[2],a=t[0],r=t[1],l=t[2];return[n*l-i*r,i*a-s*l,s*r-n*a,0]},cross3Vec3(e,t,s){s||(s=e);const n=e[0],i=e[1],a=e[2],r=t[0],l=t[1],o=t[2];return s[0]=i*o-a*l,s[1]=a*r-n*o,s[2]=n*l-i*r,s},sqLenVec4:e=>h.dotVec4(e,e),lenVec4:e=>Math.sqrt(h.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>h.dotVec3(e,e),sqLenVec2:e=>h.dotVec2(e,e),lenVec3:e=>Math.sqrt(h.sqLenVec3(e)),distVec3:(()=>{const e=new r(3);return(t,s)=>h.lenVec3(h.subVec3(t,s,e))})(),lenVec2:e=>Math.sqrt(h.sqLenVec2(e)),distVec2:(()=>{const e=new r(2);return(t,s)=>h.lenVec2(h.subVec2(t,s,e))})(),rcpVec3:(e,t)=>h.divScalarVec3(1,e,t),normalizeVec4(e,t){const s=1/h.lenVec4(e);return h.mulVec4Scalar(e,s,t)},normalizeVec3(e,t){const s=1/h.lenVec3(e);return h.mulVec3Scalar(e,s,t)},normalizeVec2(e,t){const s=1/h.lenVec2(e);return h.mulVec2Scalar(e,s,t)},angleVec3(e,t){let s=h.dotVec3(e,t)/Math.sqrt(h.sqLenVec3(e)*h.sqLenVec3(t));return s=s<-1?-1:s>1?1:s,Math.acos(s)},vec3FromMat4Scale:(()=>{const e=new r(3);return(t,s)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],s[0]=h.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],s[1]=h.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],s[2]=h.lenVec3(e),s)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let s=0,n=(t=Array.prototype.slice.call(t)).length;s<n;s++)t[s]=e(t[s]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||h.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>h.m4s(0),setMat4ToOnes:()=>h.m4s(1),diagonalMat4v:e=>new r([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,s,n)=>h.diagonalMat4v([e,t,s,n]),diagonalMat4s:e=>h.diagonalMat4c(e,e,e,e),identityMat4:(e=new r(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new r(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]+t[0],s[1]=e[1]+t[1],s[2]=e[2]+t[2],s[3]=e[3]+t[3],s[4]=e[4]+t[4],s[5]=e[5]+t[5],s[6]=e[6]+t[6],s[7]=e[7]+t[7],s[8]=e[8]+t[8],s[9]=e[9]+t[9],s[10]=e[10]+t[10],s[11]=e[11]+t[11],s[12]=e[12]+t[12],s[13]=e[13]+t[13],s[14]=e[14]+t[14],s[15]=e[15]+t[15],s),addMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]+t,s[1]=e[1]+t,s[2]=e[2]+t,s[3]=e[3]+t,s[4]=e[4]+t,s[5]=e[5]+t,s[6]=e[6]+t,s[7]=e[7]+t,s[8]=e[8]+t,s[9]=e[9]+t,s[10]=e[10]+t,s[11]=e[11]+t,s[12]=e[12]+t,s[13]=e[13]+t,s[14]=e[14]+t,s[15]=e[15]+t,s),addScalarMat4:(e,t,s)=>h.addMat4Scalar(t,e,s),subMat4:(e,t,s)=>(s||(s=e),s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],s[3]=e[3]-t[3],s[4]=e[4]-t[4],s[5]=e[5]-t[5],s[6]=e[6]-t[6],s[7]=e[7]-t[7],s[8]=e[8]-t[8],s[9]=e[9]-t[9],s[10]=e[10]-t[10],s[11]=e[11]-t[11],s[12]=e[12]-t[12],s[13]=e[13]-t[13],s[14]=e[14]-t[14],s[15]=e[15]-t[15],s),subMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]-t,s[1]=e[1]-t,s[2]=e[2]-t,s[3]=e[3]-t,s[4]=e[4]-t,s[5]=e[5]-t,s[6]=e[6]-t,s[7]=e[7]-t,s[8]=e[8]-t,s[9]=e[9]-t,s[10]=e[10]-t,s[11]=e[11]-t,s[12]=e[12]-t,s[13]=e[13]-t,s[14]=e[14]-t,s[15]=e[15]-t,s),subScalarMat4:(e,t,s)=>(s||(s=t),s[0]=e-t[0],s[1]=e-t[1],s[2]=e-t[2],s[3]=e-t[3],s[4]=e-t[4],s[5]=e-t[5],s[6]=e-t[6],s[7]=e-t[7],s[8]=e-t[8],s[9]=e-t[9],s[10]=e-t[10],s[11]=e-t[11],s[12]=e-t[12],s[13]=e-t[13],s[14]=e-t[14],s[15]=e-t[15],s),mulMat4(e,t,s){s||(s=e);const n=e[0],i=e[1],a=e[2],r=e[3],l=e[4],o=e[5],c=e[6],u=e[7],h=e[8],p=e[9],A=e[10],d=e[11],f=e[12],I=e[13],y=e[14],m=e[15],v=t[0],w=t[1],g=t[2],E=t[3],T=t[4],b=t[5],D=t[6],P=t[7],R=t[8],C=t[9],_=t[10],B=t[11],O=t[12],S=t[13],N=t[14],x=t[15];return s[0]=v*n+w*l+g*h+E*f,s[1]=v*i+w*o+g*p+E*I,s[2]=v*a+w*c+g*A+E*y,s[3]=v*r+w*u+g*d+E*m,s[4]=T*n+b*l+D*h+P*f,s[5]=T*i+b*o+D*p+P*I,s[6]=T*a+b*c+D*A+P*y,s[7]=T*r+b*u+D*d+P*m,s[8]=R*n+C*l+_*h+B*f,s[9]=R*i+C*o+_*p+B*I,s[10]=R*a+C*c+_*A+B*y,s[11]=R*r+C*u+_*d+B*m,s[12]=O*n+S*l+N*h+x*f,s[13]=O*i+S*o+N*p+x*I,s[14]=O*a+S*c+N*A+x*y,s[15]=O*r+S*u+N*d+x*m,s},mulMat3(e,t,s){s||(s=new r(9));const n=e[0],i=e[3],a=e[6],l=e[1],o=e[4],c=e[7],u=e[2],h=e[5],p=e[8],A=t[0],d=t[3],f=t[6],I=t[1],y=t[4],m=t[7],v=t[2],w=t[5],g=t[8];return s[0]=n*A+i*I+a*v,s[3]=n*d+i*y+a*w,s[6]=n*f+i*m+a*g,s[1]=l*A+o*I+c*v,s[4]=l*d+o*y+c*w,s[7]=l*f+o*m+c*g,s[2]=u*A+h*I+p*v,s[5]=u*d+h*y+p*w,s[8]=u*f+h*m+p*g,s},mulMat4Scalar:(e,t,s)=>(s||(s=e),s[0]=e[0]*t,s[1]=e[1]*t,s[2]=e[2]*t,s[3]=e[3]*t,s[4]=e[4]*t,s[5]=e[5]*t,s[6]=e[6]*t,s[7]=e[7]*t,s[8]=e[8]*t,s[9]=e[9]*t,s[10]=e[10]*t,s[11]=e[11]*t,s[12]=e[12]*t,s[13]=e[13]*t,s[14]=e[14]*t,s[15]=e[15]*t,s),mulMat4v4(e,t,s=h.vec4()){const n=t[0],i=t[1],a=t[2],r=t[3];return s[0]=e[0]*n+e[4]*i+e[8]*a+e[12]*r,s[1]=e[1]*n+e[5]*i+e[9]*a+e[13]*r,s[2]=e[2]*n+e[6]*i+e[10]*a+e[14]*r,s[3]=e[3]*n+e[7]*i+e[11]*a+e[15]*r,s},transposeMat4(e,t){const s=e[4],n=e[14],i=e[8],a=e[13],r=e[12],l=e[9];if(!t||e===t){const t=e[1],o=e[2],c=e[3],u=e[6],h=e[7],p=e[11];return e[1]=s,e[2]=i,e[3]=r,e[4]=t,e[6]=l,e[7]=a,e[8]=o,e[9]=u,e[11]=n,e[12]=c,e[13]=h,e[14]=p,e}return t[0]=e[0],t[1]=s,t[2]=i,t[3]=r,t[4]=e[1],t[5]=e[5],t[6]=l,t[7]=a,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=n,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const s=e[1],n=e[2],i=e[5];t[1]=e[3],t[2]=e[6],t[3]=s,t[5]=e[7],t[6]=n,t[7]=i}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],s=e[1],n=e[2],i=e[3],a=e[4],r=e[5],l=e[6],o=e[7],c=e[8],u=e[9],h=e[10],p=e[11],A=e[12],d=e[13],f=e[14],I=e[15];return A*u*l*i-c*d*l*i-A*r*h*i+a*d*h*i+c*r*f*i-a*u*f*i-A*u*n*o+c*d*n*o+A*s*h*o-t*d*h*o-c*s*f*o+t*u*f*o+A*r*n*p-a*d*n*p-A*s*l*p+t*d*l*p+a*s*f*p-t*r*f*p-c*r*n*I+a*u*n*I+c*s*l*I-t*u*l*I-a*s*h*I+t*r*h*I},inverseMat4(e,t){t||(t=e);const s=e[0],n=e[1],i=e[2],a=e[3],r=e[4],l=e[5],o=e[6],c=e[7],u=e[8],h=e[9],p=e[10],A=e[11],d=e[12],f=e[13],I=e[14],y=e[15],m=s*l-n*r,v=s*o-i*r,w=s*c-a*r,g=n*o-i*l,E=n*c-a*l,T=i*c-a*o,b=u*f-h*d,D=u*I-p*d,P=u*y-A*d,R=h*I-p*f,C=h*y-A*f,_=p*y-A*I,B=1/(m*_-v*C+w*R+g*P-E*D+T*b);return t[0]=(l*_-o*C+c*R)*B,t[1]=(-n*_+i*C-a*R)*B,t[2]=(f*T-I*E+y*g)*B,t[3]=(-h*T+p*E-A*g)*B,t[4]=(-r*_+o*P-c*D)*B,t[5]=(s*_-i*P+a*D)*B,t[6]=(-d*T+I*w-y*v)*B,t[7]=(u*T-p*w+A*v)*B,t[8]=(r*C-l*P+c*b)*B,t[9]=(-s*C+n*P-a*b)*B,t[10]=(d*E-f*w+y*m)*B,t[11]=(-u*E+h*w-A*m)*B,t[12]=(-r*R+l*D-o*b)*B,t[13]=(s*R-n*D+i*b)*B,t[14]=(-d*g+f*v-I*m)*B,t[15]=(u*g-h*v+p*m)*B,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const s=t||h.identityMat4();return s[12]=e[0],s[13]=e[1],s[14]=e[2],s},translationMat3v(e,t){const s=t||h.identityMat3();return s[6]=e[0],s[7]=e[1],s},translationMat4c:(()=>{const e=new r(3);return(t,s,n,i)=>(e[0]=t,e[1]=s,e[2]=n,h.translationMat4v(e,i))})(),translationMat4s:(e,t)=>h.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>h.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,s,n){const i=n[3];n[0]+=i*e,n[1]+=i*t,n[2]+=i*s;const a=n[7];n[4]+=a*e,n[5]+=a*t,n[6]+=a*s;const r=n[11];n[8]+=r*e,n[9]+=r*t,n[10]+=r*s;const l=n[15];return n[12]+=l*e,n[13]+=l*t,n[14]+=l*s,n},setMat4Translation:(e,t,s)=>(s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=e[15],s),rotationMat4v(e,t,s){const n=h.normalizeVec4([t[0],t[1],t[2],0],[]),i=Math.sin(e),a=Math.cos(e),r=1-a,l=n[0],o=n[1],c=n[2];let u,p,A,d,f,I;return u=l*o,p=o*c,A=c*l,d=l*i,f=o*i,I=c*i,(s=s||h.mat4())[0]=r*l*l+a,s[1]=r*u+I,s[2]=r*A-f,s[3]=0,s[4]=r*u-I,s[5]=r*o*o+a,s[6]=r*p+d,s[7]=0,s[8]=r*A+f,s[9]=r*p-d,s[10]=r*c*c+a,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,s},rotationMat4c:(e,t,s,n,i)=>h.rotationMat4v(e,[t,s,n],i),scalingMat4v:(e,t=h.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=h.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new r(3);return(t,s,n,i)=>(e[0]=t,e[1]=s,e[2]=n,h.scalingMat4v(e,i))})(),scaleMat4c:(e,t,s,n)=>(n[0]*=e,n[4]*=t,n[8]*=s,n[1]*=e,n[5]*=t,n[9]*=s,n[2]*=e,n[6]*=t,n[10]*=s,n[3]*=e,n[7]*=t,n[11]*=s,n),scaleMat4v(e,t){const s=e[0],n=e[1],i=e[2];return t[0]*=s,t[4]*=n,t[8]*=i,t[1]*=s,t[5]*=n,t[9]*=i,t[2]*=s,t[6]*=n,t[10]*=i,t[3]*=s,t[7]*=n,t[11]*=i,t},scalingMat4s:e=>h.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,s=h.mat4()){const n=e[0],i=e[1],a=e[2],r=e[3],l=n+n,o=i+i,c=a+a,u=n*l,p=n*o,A=n*c,d=i*o,f=i*c,I=a*c,y=r*l,m=r*o,v=r*c;return s[0]=1-(d+I),s[1]=p+v,s[2]=A-m,s[3]=0,s[4]=p-v,s[5]=1-(u+I),s[6]=f+y,s[7]=0,s[8]=A+m,s[9]=f-y,s[10]=1-(u+d),s[11]=0,s[12]=t[0],s[13]=t[1],s[14]=t[2],s[15]=1,s},mat4ToEuler(e,t,s=h.vec4()){const n=h.clamp,i=e[0],a=e[4],r=e[8],l=e[1],o=e[5],c=e[9],u=e[2],p=e[6],A=e[10];return"XYZ"===t?(s[1]=Math.asin(n(r,-1,1)),Math.abs(r)<.99999?(s[0]=Math.atan2(-c,A),s[2]=Math.atan2(-a,i)):(s[0]=Math.atan2(p,o),s[2]=0)):"YXZ"===t?(s[0]=Math.asin(-n(c,-1,1)),Math.abs(c)<.99999?(s[1]=Math.atan2(r,A),s[2]=Math.atan2(l,o)):(s[1]=Math.atan2(-u,i),s[2]=0)):"ZXY"===t?(s[0]=Math.asin(n(p,-1,1)),Math.abs(p)<.99999?(s[1]=Math.atan2(-u,A),s[2]=Math.atan2(-a,o)):(s[1]=0,s[2]=Math.atan2(l,i))):"ZYX"===t?(s[1]=Math.asin(-n(u,-1,1)),Math.abs(u)<.99999?(s[0]=Math.atan2(p,A),s[2]=Math.atan2(l,i)):(s[0]=0,s[2]=Math.atan2(-a,o))):"YZX"===t?(s[2]=Math.asin(n(l,-1,1)),Math.abs(l)<.99999?(s[0]=Math.atan2(-c,o),s[1]=Math.atan2(-u,i)):(s[0]=0,s[1]=Math.atan2(r,A))):"XZY"===t&&(s[2]=Math.asin(-n(a,-1,1)),Math.abs(a)<.99999?(s[0]=Math.atan2(p,o),s[1]=Math.atan2(r,i)):(s[0]=Math.atan2(-c,A),s[1]=0)),s},composeMat4:(e,t,s,n=h.mat4())=>(h.quaternionToRotationMat4(t,n),h.scaleMat4v(s,n),h.translateMat4v(e,n),n),decomposeMat4:(()=>{const e=new r(3),t=new r(16);return function(s,n,i,a){e[0]=s[0],e[1]=s[1],e[2]=s[2];let r=h.lenVec3(e);e[0]=s[4],e[1]=s[5],e[2]=s[6];const l=h.lenVec3(e);e[8]=s[8],e[9]=s[9],e[10]=s[10];const o=h.lenVec3(e);h.determinantMat4(s)<0&&(r=-r),n[0]=s[12],n[1]=s[13],n[2]=s[14],t.set(s);const c=1/r,u=1/l,p=1/o;return t[0]*=c,t[1]*=c,t[2]*=c,t[4]*=u,t[5]*=u,t[6]*=u,t[8]*=p,t[9]*=p,t[10]*=p,h.mat4ToQuaternion(t,i),a[0]=r,a[1]=l,a[2]=o,this}})(),getColMat4(e,t){const s=4*t;return[e[s],e[s+1],e[s+2],e[s+3]]},setRowMat4(e,t,s){e[t]=s[0],e[t+4]=s[1],e[t+8]=s[2],e[t+12]=s[3]},lookAtMat4v(e,t,s,n){n||(n=h.mat4());const i=e[0],a=e[1],r=e[2],l=s[0],o=s[1],c=s[2],u=t[0],p=t[1],A=t[2];if(i===u&&a===p&&r===A)return h.identityMat4();let d,f,I,y,m,v,w,g,E,T;return d=i-u,f=a-p,I=r-A,T=1/Math.sqrt(d*d+f*f+I*I),d*=T,f*=T,I*=T,y=o*I-c*f,m=c*d-l*I,v=l*f-o*d,T=Math.sqrt(y*y+m*m+v*v),T?(T=1/T,y*=T,m*=T,v*=T):(y=0,m=0,v=0),w=f*v-I*m,g=I*y-d*v,E=d*m-f*y,T=Math.sqrt(w*w+g*g+E*E),T?(T=1/T,w*=T,g*=T,E*=T):(w=0,g=0,E=0),n[0]=y,n[1]=w,n[2]=d,n[3]=0,n[4]=m,n[5]=g,n[6]=f,n[7]=0,n[8]=v,n[9]=E,n[10]=I,n[11]=0,n[12]=-(y*i+m*a+v*r),n[13]=-(w*i+g*a+E*r),n[14]=-(d*i+f*a+I*r),n[15]=1,n},lookAtMat4c:(e,t,s,n,i,a,r,l,o)=>h.lookAtMat4v([e,t,s],[n,i,a],[r,l,o],[]),orthoMat4c(e,t,s,n,i,a,r){r||(r=h.mat4());const l=t-e,o=n-s,c=a-i;return r[0]=2/l,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=2/o,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=-2/c,r[11]=0,r[12]=-(e+t)/l,r[13]=-(n+s)/o,r[14]=-(a+i)/c,r[15]=1,r},frustumMat4v(e,t,s){s||(s=h.mat4());const n=[e[0],e[1],e[2],0],i=[t[0],t[1],t[2],0];h.addVec4(i,n,o),h.subVec4(i,n,c);const a=2*n[2],r=c[0],l=c[1],u=c[2];return s[0]=a/r,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=a/l,s[6]=0,s[7]=0,s[8]=o[0]/r,s[9]=o[1]/l,s[10]=-o[2]/u,s[11]=-1,s[12]=0,s[13]=0,s[14]=-a*i[2]/u,s[15]=0,s},frustumMat4(e,t,s,n,i,a,r){r||(r=h.mat4());const l=t-e,o=n-s,c=a-i;return r[0]=2*i/l,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=2*i/o,r[6]=0,r[7]=0,r[8]=(t+e)/l,r[9]=(n+s)/o,r[10]=-(a+i)/c,r[11]=-1,r[12]=0,r[13]=0,r[14]=-a*i*2/c,r[15]=0,r},perspectiveMat4(e,t,s,n,i){const a=[],r=[];return a[2]=s,r[2]=n,r[1]=a[2]*Math.tan(e/2),a[1]=-r[1],r[0]=r[1]*t,a[0]=-r[0],h.frustumMat4v(a,r,i)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,s=h.vec3()){const n=t[0],i=t[1],a=t[2];return s[0]=e[0]*n+e[4]*i+e[8]*a+e[12],s[1]=e[1]*n+e[5]*i+e[9]*a+e[13],s[2]=e[2]*n+e[6]*i+e[10]*a+e[14],s},transformPoint4:(e,t,s=h.vec4())=>(s[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],s[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],s[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],s[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],s),transformPoints3(e,t,s){const n=s||[],i=t.length;let a,r,l,o;const c=e[0],u=e[1],h=e[2],p=e[3],A=e[4],d=e[5],f=e[6],I=e[7],y=e[8],m=e[9],v=e[10],w=e[11],g=e[12],E=e[13],T=e[14],b=e[15];let D;for(let e=0;e<i;++e)o=t[e],a=o[0],r=o[1],l=o[2],D=n[e]||(n[e]=[0,0,0]),D[0]=c*a+A*r+y*l+g,D[1]=u*a+d*r+m*l+E,D[2]=h*a+f*r+v*l+T,D[3]=p*a+I*r+w*l+b;return n.length=i,n},transformPositions3(e,t,s=t){let n;const i=t.length;let a,r,l;const o=e[0],c=e[1],u=e[2];e[3];const h=e[4],p=e[5],A=e[6];e[7];const d=e[8],f=e[9],I=e[10];e[11];const y=e[12],m=e[13],v=e[14];for(e[15],n=0;n<i;n+=3)a=t[n+0],r=t[n+1],l=t[n+2],s[n+0]=o*a+h*r+d*l+y,s[n+1]=c*a+p*r+f*l+m,s[n+2]=u*a+A*r+I*l+v;return s},transformPositions4(e,t,s=t){let n;const i=t.length;let a,r,l;const o=e[0],c=e[1],u=e[2],h=e[3],p=e[4],A=e[5],d=e[6],f=e[7],I=e[8],y=e[9],m=e[10],v=e[11],w=e[12],g=e[13],E=e[14],T=e[15];for(n=0;n<i;n+=4)a=t[n+0],r=t[n+1],l=t[n+2],s[n+0]=o*a+p*r+I*l+w,s[n+1]=c*a+A*r+y*l+g,s[n+2]=u*a+d*r+m*l+E,s[n+3]=h*a+f*r+v*l+T;return s},transformVec3(e,t,s){const n=t[0],i=t[1],a=t[2];return(s=s||this.vec3())[0]=e[0]*n+e[4]*i+e[8]*a,s[1]=e[1]*n+e[5]*i+e[9]*a,s[2]=e[2]*n+e[6]*i+e[10]*a,s},transformVec4(e,t,s){const n=t[0],i=t[1],a=t[2],r=t[3];return(s=s||h.vec4())[0]=e[0]*n+e[4]*i+e[8]*a+e[12]*r,s[1]=e[1]*n+e[5]*i+e[9]*a+e[13]*r,s[2]=e[2]*n+e[6]*i+e[10]*a+e[14]*r,s[3]=e[3]*n+e[7]*i+e[11]*a+e[15]*r,s},rotateVec2(e,t,s,n=e){const i=Math.cos(s),a=Math.sin(s),r=e[0]-t[0],l=e[1]-t[1];return n[0]=r*i-l*a+t[0],n[1]=r*a+l*i+t[1],e},rotateVec3X(e,t,s,n){const i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0],a[1]=i[1]*Math.cos(s)-i[2]*Math.sin(s),a[2]=i[1]*Math.sin(s)+i[2]*Math.cos(s),n[0]=a[0]+t[0],n[1]=a[1]+t[1],n[2]=a[2]+t[2],n},rotateVec3Y(e,t,s,n){const i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[2]*Math.sin(s)+i[0]*Math.cos(s),a[1]=i[1],a[2]=i[2]*Math.cos(s)-i[0]*Math.sin(s),n[0]=a[0]+t[0],n[1]=a[1]+t[1],n[2]=a[2]+t[2],n},rotateVec3Z(e,t,s,n){const i=[],a=[];return i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],a[0]=i[0]*Math.cos(s)-i[1]*Math.sin(s),a[1]=i[0]*Math.sin(s)+i[1]*Math.cos(s),a[2]=i[2],n[0]=a[0]+t[0],n[1]=a[1]+t[1],n[2]=a[2]+t[2],n},projectVec4(e,t){const s=1/e[3];return(t=t||h.vec2())[0]=e[0]*s,t[1]=e[1]*s,t},unprojectVec3:(()=>{const e=new r(16),t=new r(16),s=new r(16);return function(n,i,a,r){return this.transformVec3(this.mulMat4(this.inverseMat4(i,e),this.inverseMat4(a,t),s),n,r)}})(),lerpVec3(e,t,s,n,i,a){const r=a||h.vec3(),l=(e-t)/(s-t);return r[0]=n[0]+l*(i[0]-n[0]),r[1]=n[1]+l*(i[1]-n[1]),r[2]=n[2]+l*(i[2]-n[2]),r},lerpMat4(e,t,s,n,i,a){const r=a||h.mat4(),l=(e-t)/(s-t);return r[0]=n[0]+l*(i[0]-n[0]),r[1]=n[1]+l*(i[1]-n[1]),r[2]=n[2]+l*(i[2]-n[2]),r[3]=n[3]+l*(i[3]-n[3]),r[4]=n[4]+l*(i[4]-n[4]),r[5]=n[5]+l*(i[5]-n[5]),r[6]=n[6]+l*(i[6]-n[6]),r[7]=n[7]+l*(i[7]-n[7]),r[8]=n[8]+l*(i[8]-n[8]),r[9]=n[9]+l*(i[9]-n[9]),r[10]=n[10]+l*(i[10]-n[10]),r[11]=n[11]+l*(i[11]-n[11]),r[12]=n[12]+l*(i[12]-n[12]),r[13]=n[13]+l*(i[13]-n[13]),r[14]=n[14]+l*(i[14]-n[14]),r[15]=n[15]+l*(i[15]-n[15]),r},flatten(e){const t=[];let s,n,i,a,r;for(s=0,n=e.length;s<n;s++)for(r=e[s],i=0,a=r.length;i<a;i++)t.push(r[i]);return t},identityQuaternion:(e=h.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,s=h.vec4()){const n=e[0]*h.DEGTORAD/2,i=e[1]*h.DEGTORAD/2,a=e[2]*h.DEGTORAD/2,r=Math.cos(n),l=Math.cos(i),o=Math.cos(a),c=Math.sin(n),u=Math.sin(i),p=Math.sin(a);return"XYZ"===t?(s[0]=c*l*o+r*u*p,s[1]=r*u*o-c*l*p,s[2]=r*l*p+c*u*o,s[3]=r*l*o-c*u*p):"YXZ"===t?(s[0]=c*l*o+r*u*p,s[1]=r*u*o-c*l*p,s[2]=r*l*p-c*u*o,s[3]=r*l*o+c*u*p):"ZXY"===t?(s[0]=c*l*o-r*u*p,s[1]=r*u*o+c*l*p,s[2]=r*l*p+c*u*o,s[3]=r*l*o-c*u*p):"ZYX"===t?(s[0]=c*l*o-r*u*p,s[1]=r*u*o+c*l*p,s[2]=r*l*p-c*u*o,s[3]=r*l*o+c*u*p):"YZX"===t?(s[0]=c*l*o+r*u*p,s[1]=r*u*o+c*l*p,s[2]=r*l*p-c*u*o,s[3]=r*l*o-c*u*p):"XZY"===t&&(s[0]=c*l*o-r*u*p,s[1]=r*u*o-c*l*p,s[2]=r*l*p+c*u*o,s[3]=r*l*o+c*u*p),s},mat4ToQuaternion(e,t=h.vec4()){const s=e[0],n=e[4],i=e[8],a=e[1],r=e[5],l=e[9],o=e[2],c=e[6],u=e[10];let p;const A=s+r+u;return A>0?(p=.5/Math.sqrt(A+1),t[3]=.25/p,t[0]=(c-l)*p,t[1]=(i-o)*p,t[2]=(a-n)*p):s>r&&s>u?(p=2*Math.sqrt(1+s-r-u),t[3]=(c-l)/p,t[0]=.25*p,t[1]=(n+a)/p,t[2]=(i+o)/p):r>u?(p=2*Math.sqrt(1+r-s-u),t[3]=(i-o)/p,t[0]=(n+a)/p,t[1]=.25*p,t[2]=(l+c)/p):(p=2*Math.sqrt(1+u-s-r),t[3]=(a-n)/p,t[0]=(i+o)/p,t[1]=(l+c)/p,t[2]=.25*p),t},vec3PairToQuaternion(e,t,s=h.vec4()){const n=Math.sqrt(h.dotVec3(e,e)*h.dotVec3(t,t));let i=n+h.dotVec3(e,t);return i<1e-8*n?(i=0,Math.abs(e[0])>Math.abs(e[2])?(s[0]=-e[1],s[1]=e[0],s[2]=0):(s[0]=0,s[1]=-e[2],s[2]=e[1])):h.cross3Vec3(e,t,s),s[3]=i,h.normalizeQuaternion(s)},angleAxisToQuaternion(e,t=h.vec4()){const s=e[3]/2,n=Math.sin(s);return t[0]=n*e[0],t[1]=n*e[1],t[2]=n*e[2],t[3]=Math.cos(s),t},quaternionToEuler:(()=>{const e=new r(16);return(t,s,n)=>(n=n||h.vec3(),h.quaternionToRotationMat4(t,e),h.mat4ToEuler(e,s,n),n)})(),mulQuaternions(e,t,s=h.vec4()){const n=e[0],i=e[1],a=e[2],r=e[3],l=t[0],o=t[1],c=t[2],u=t[3];return s[0]=r*l+n*u+i*c-a*o,s[1]=r*o+i*u+a*l-n*c,s[2]=r*c+a*u+n*o-i*l,s[3]=r*u-n*l-i*o-a*c,s},vec3ApplyQuaternion(e,t,s=h.vec3()){const n=t[0],i=t[1],a=t[2],r=e[0],l=e[1],o=e[2],c=e[3],u=c*n+l*a-o*i,p=c*i+o*n-r*a,A=c*a+r*i-l*n,d=-r*n-l*i-o*a;return s[0]=u*c+d*-r+p*-o-A*-l,s[1]=p*c+d*-l+A*-r-u*-o,s[2]=A*c+d*-o+u*-l-p*-r,s},quaternionToMat4(e,t){t=h.identityMat4(t);const s=e[0],n=e[1],i=e[2],a=e[3],r=2*s,l=2*n,o=2*i,c=r*a,u=l*a,p=o*a,A=r*s,d=l*s,f=o*s,I=l*n,y=o*n,m=o*i;return t[0]=1-(I+m),t[1]=d+p,t[2]=f-u,t[4]=d-p,t[5]=1-(A+m),t[6]=y+c,t[8]=f+u,t[9]=y-c,t[10]=1-(A+I),t},quaternionToRotationMat4(e,t){const s=e[0],n=e[1],i=e[2],a=e[3],r=s+s,l=n+n,o=i+i,c=s*r,u=s*l,h=s*o,p=n*l,A=n*o,d=i*o,f=a*r,I=a*l,y=a*o;return t[0]=1-(p+d),t[4]=u-y,t[8]=h+I,t[1]=u+y,t[5]=1-(c+d),t[9]=A-f,t[2]=h-I,t[6]=A+f,t[10]=1-(c+p),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const s=h.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s,t[3]=e[3]/s,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>h.normalizeQuaternion(h.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=h.vec4()){const s=(e=h.normalizeQuaternion(e,u))[3],n=2*Math.acos(s),i=Math.sqrt(1-s*s);return i<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i),t[3]=n,t},AABB3:e=>new r(e||6),AABB2:e=>new r(e||4),OBB3:e=>new r(e||32),OBB2:e=>new r(e||16),Sphere3:(e,t,s,n)=>new r([e,t,s,n]),transformOBB3(e,t,s=t){let n;const i=t.length;let a,r,l;const o=e[0],c=e[1],u=e[2],h=e[3],p=e[4],A=e[5],d=e[6],f=e[7],I=e[8],y=e[9],m=e[10],v=e[11],w=e[12],g=e[13],E=e[14],T=e[15];for(n=0;n<i;n+=4)a=t[n+0],r=t[n+1],l=t[n+2],s[n+0]=o*a+p*r+I*l+w,s[n+1]=c*a+A*r+y*l+g,s[n+2]=u*a+d*r+m*l+E,s[n+3]=h*a+f*r+v*l+T;return s},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new r(3),t=new r(3),s=new r(3);return n=>(e[0]=n[0],e[1]=n[1],e[2]=n[2],t[0]=n[3],t[1]=n[4],t[2]=n[5],h.subVec3(t,e,s),Math.abs(h.lenVec3(s)))})(),getAABB3DiagPoint:(()=>{const e=new r(3),t=new r(3),s=new r(3);return(n,i)=>{e[0]=n[0],e[1]=n[1],e[2]=n[2],t[0]=n[3],t[1]=n[4],t[2]=n[5];const a=h.subVec3(t,e,s),r=i[0]-n[0],l=n[3]-i[0],o=i[1]-n[1],c=n[4]-i[1],u=i[2]-n[2],p=n[5]-i[2];return a[0]+=r>l?r:l,a[1]+=o>c?o:c,a[2]+=u>p?u:p,Math.abs(h.lenVec3(a))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const s=t||h.vec3();return s[0]=(e[0]+e[3])/2,s[1]=(e[1]+e[4])/2,s[2]=(e[2]+e[5])/2,s},getAABB2Center(e,t){const s=t||h.vec2();return s[0]=(e[2]+e[0])/2,s[1]=(e[3]+e[1])/2,s},collapseAABB3:(e=h.AABB3())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MAX_DOUBLE,e[3]=h.MIN_DOUBLE,e[4]=h.MIN_DOUBLE,e[5]=h.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=h.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new r(3);return(t,s,n)=>{s=s||h.AABB3();let i,a,r,l=h.MAX_DOUBLE,o=h.MAX_DOUBLE,c=h.MAX_DOUBLE,u=h.MIN_DOUBLE,p=h.MIN_DOUBLE,A=h.MIN_DOUBLE;for(let s=0,d=t.length;s<d;s+=3)n?(e[0]=t[s+0],e[1]=t[s+1],e[2]=t[s+2],h.decompressPosition(e,n,e),i=e[0],a=e[1],r=e[2]):(i=t[s+0],a=t[s+1],r=t[s+2]),i<l&&(l=i),a<o&&(o=a),r<c&&(c=r),i>u&&(u=i),a>p&&(p=a),r>A&&(A=r);return s[0]=l,s[1]=o,s[2]=c,s[3]=u,s[4]=p,s[5]=A,s}})(),OBB3ToAABB3(e,t=h.AABB3()){let s,n,i,a=h.MAX_DOUBLE,r=h.MAX_DOUBLE,l=h.MAX_DOUBLE,o=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)s=e[t+0],n=e[t+1],i=e[t+2],s<a&&(a=s),n<r&&(r=n),i<l&&(l=i),s>o&&(o=s),n>c&&(c=n),i>u&&(u=i);return t[0]=a,t[1]=r,t[2]=l,t[3]=o,t[4]=c,t[5]=u,t},points3ToAABB3(e,t=h.AABB3()){let s,n,i,a=h.MAX_DOUBLE,r=h.MAX_DOUBLE,l=h.MAX_DOUBLE,o=h.MIN_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)s=e[t][0],n=e[t][1],i=e[t][2],s<a&&(a=s),n<r&&(r=n),i<l&&(l=i),s>o&&(o=s),n>c&&(c=n),i>u&&(u=i);return t[0]=a,t[1]=r,t[2]=l,t[3]=o,t[4]=c,t[5]=u,t},points3ToSphere3:(()=>{const e=new r(3);return(t,s)=>{s=s||h.vec4();let n,i=0,a=0,r=0;const l=t.length;for(n=0;n<l;n++)i+=t[n][0],a+=t[n][1],r+=t[n][2];s[0]=i/l,s[1]=a/l,s[2]=r/l;let o,c=0;for(n=0;n<l;n++)o=Math.abs(h.lenVec3(h.subVec3(t[n],s,e))),o>c&&(c=o);return s[3]=c,s}})(),positions3ToSphere3:(()=>{const e=new r(3),t=new r(3);return(s,n)=>{n=n||h.vec4();let i,a=0,r=0,l=0;const o=s.length;let c=0;for(i=0;i<o;i+=3)a+=s[i],r+=s[i+1],l+=s[i+2];const u=o/3;let p;for(n[0]=a/u,n[1]=r/u,n[2]=l/u,i=0;i<o;i+=3)e[0]=s[i],e[1]=s[i+1],e[2]=s[i+2],p=Math.abs(h.lenVec3(h.subVec3(e,n,t))),p>c&&(c=p);return n[3]=c,n}})(),OBB3ToSphere3:(()=>{const e=new r(3),t=new r(3);return(s,n)=>{n=n||h.vec4();let i,a=0,r=0,l=0;const o=s.length,c=o/4;for(i=0;i<o;i+=4)a+=s[i+0],r+=s[i+1],l+=s[i+2];n[0]=a/c,n[1]=r/c,n[2]=l/c;let u,p=0;for(i=0;i<o;i+=4)e[0]=s[i+0],e[1]=s[i+1],e[2]=s[i+2],u=Math.abs(h.lenVec3(h.subVec3(e,n,t))),u>p&&(p=u);return n[3]=p,n}})(),getSphere3Center:(e,t=h.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=h.vec3()){let s=0,n=0,i=0;for(var a=0,r=e.length;a<r;a+=3)s+=e[a+0],n+=e[a+1],i+=e[a+2];const l=e.length/3;return t[0]=s/l,t[1]=n/l,t[2]=i/l,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var s,n,i,a=0,r=t.length;a<r;a+=3)s=t[a],n=t[a+1],i=t[a+2],e[0]>s&&(e[0]=s),e[1]>n&&(e[1]=n),e[2]>i&&(e[2]=i),e[3]<s&&(e[3]=s),e[4]<n&&(e[4]=n),e[5]<i&&(e[5]=i);return e},collapseAABB2:(e=h.AABB2())=>(e[0]=h.MAX_DOUBLE,e[1]=h.MAX_DOUBLE,e[2]=h.MIN_DOUBLE,e[3]=h.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],planeAABB3Intersect(e,t,s){let n,i;e[0]>0?(n=e[0]*s[0],i=e[0]*s[3]):(n=e[0]*s[3],i=e[0]*s[0]),e[1]>0?(n+=e[1]*s[1],i+=e[1]*s[4]):(n+=e[1]*s[4],i+=e[1]*s[1]),e[2]>0?(n+=e[2]*s[2],i+=e[2]*s[5]):(n+=e[2]*s[5],i+=e[2]*s[2]);if(n<=-t&&i<=-t)return-1;return n>=-t&&i>=-t?1:0},OBB3ToAABB2(e,t=h.AABB2()){let s,n,i,a,r=h.MAX_DOUBLE,l=h.MAX_DOUBLE,o=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,u=e.length;t<u;t+=4)s=e[t+0],n=e[t+1],i=e[t+3]||1,a=1/i,s*=a,n*=a,s<r&&(r=s),n<l&&(l=n),s>o&&(o=s),n>c&&(c=n);return t[0]=r,t[1]=l,t[2]=o,t[3]=c,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,s,n=e){const i=.5*(e[0]+1),a=.5*(e[1]+1),r=.5*(e[2]+1),l=.5*(e[3]+1);return n[0]=Math.floor(i*t),n[1]=s-Math.floor(l*s),n[2]=Math.floor(r*t),n[3]=s-Math.floor(a*s),n},tangentQuadraticBezier:(e,t,s,n)=>2*(1-e)*(s-t)+2*e*(n-s),tangentQuadraticBezier3:(e,t,s,n,i)=>-3*t*(1-e)*(1-e)+3*s*(1-e)*(1-e)-6*e*s*(1-e)+6*e*n*(1-e)-3*e*e*n+3*e*e*i,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,s,n,i){const a=.5*(s-e),r=.5*(n-t),l=i*i;return(2*t-2*s+a+r)*(i*l)+(-3*t+3*s-2*a-r)*l+a*i+t},b2p0(e,t){const s=1-e;return s*s*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,s,n){return this.b2p0(e,t)+this.b2p1(e,s)+this.b2p2(e,n)},b3p0(e,t){const s=1-e;return s*s*s*t},b3p1(e,t){const s=1-e;return 3*s*s*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,s,n,i){return this.b3p0(e,t)+this.b3p1(e,s)+this.b3p2(e,n)+this.b3p3(e,i)},triangleNormal(e,t,s,n=h.vec3()){const i=t[0]-e[0],a=t[1]-e[1],r=t[2]-e[2],l=s[0]-e[0],o=s[1]-e[1],c=s[2]-e[2],u=a*c-r*o,p=r*l-i*c,A=i*o-a*l,d=Math.sqrt(u*u+p*p+A*A);return 0===d?(n[0]=0,n[1]=0,n[2]=0):(n[0]=u/d,n[1]=p/d,n[2]=A/d),n},rayTriangleIntersect:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3),i=new r(3);return(a,r,l,o,c,u)=>{u=u||h.vec3();const p=h.subVec3(o,l,e),A=h.subVec3(c,l,t),d=h.cross3Vec3(r,A,s),f=h.dotVec3(p,d);if(f<1e-6)return null;const I=h.subVec3(a,l,n),y=h.dotVec3(I,d);if(y<0||y>f)return null;const m=h.cross3Vec3(I,p,i),v=h.dotVec3(r,m);if(v<0||y+v>f)return null;const w=h.dotVec3(A,m)/f;return u[0]=a[0]+w*r[0],u[1]=a[1]+w*r[1],u[2]=a[2]+w*r[2],u}})(),rayPlaneIntersect:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3);return(i,a,r,l,o,c)=>{c=c||h.vec3(),a=h.normalizeVec3(a,e);const u=h.subVec3(l,r,t),p=h.subVec3(o,r,s),A=h.cross3Vec3(u,p,n);h.normalizeVec3(A,A);const d=-h.dotVec3(r,A),f=-(h.dotVec3(i,A)+d)/h.dotVec3(a,A);return c[0]=i[0]+f*a[0],c[1]=i[1]+f*a[1],c[2]=i[2]+f*a[2],c}})(),cartesianToBarycentric:(()=>{const e=new r(3),t=new r(3),s=new r(3);return(n,i,a,r,l)=>{const o=h.subVec3(r,i,e),c=h.subVec3(a,i,t),u=h.subVec3(n,i,s),p=h.dotVec3(o,o),A=h.dotVec3(o,c),d=h.dotVec3(o,u),f=h.dotVec3(c,c),I=h.dotVec3(c,u),y=p*f-A*A;if(0===y)return null;const m=1/y,v=(f*d-A*I)*m,w=(p*I-A*d)*m;return l[0]=1-v-w,l[1]=w,l[2]=v,l}})(),barycentricInsideTriangle(e){const t=e[1],s=e[2];return s>=0&&t>=0&&s+t<1},barycentricToCartesian(e,t,s,n,i=h.vec3()){const a=e[0],r=e[1],l=e[2];return i[0]=t[0]*a+s[0]*r+n[0]*l,i[1]=t[1]*a+s[1]*r+n[1]*l,i[2]=t[2]*a+s[2]*r+n[2]*l,i},mergeVertices(e,t,s,n){const i={},a=[],r=[],l=t?[]:null,o=s?[]:null,c=[];let u,h,p,A;const d=1e4;let f,I,y=0;for(f=0,I=e.length;f<I;f+=3)u=e[f],h=e[f+1],p=e[f+2],A=`${Math.round(u*d)}_${Math.round(h*d)}_${Math.round(p*d)}`,void 0===i[A]&&(i[A]=r.length/3,r.push(u),r.push(h),r.push(p),t&&(l.push(t[f]),l.push(t[f+1]),l.push(t[f+2])),s&&(o.push(s[y]),o.push(s[y+1]))),a[f/3]=i[A],y+=2;for(f=0,I=n.length;f<I;f++)c[f]=a[n[f]];const m={positions:r,indices:c};return l&&(m.normals=l),o&&(m.uv=o),m},buildNormals:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3),i=new r(3),a=new r(3);return(r,l,o)=>{let c,u;const p=new Array(r.length/3);let A,d,f,I,y,m,v;for(c=0,u=l.length;c<u;c+=3){A=l[c],d=l[c+1],f=l[c+2],e[0]=r[3*A],e[1]=r[3*A+1],e[2]=r[3*A+2],t[0]=r[3*d],t[1]=r[3*d+1],t[2]=r[3*d+2],s[0]=r[3*f],s[1]=r[3*f+1],s[2]=r[3*f+2],h.subVec3(t,e,n),h.subVec3(s,e,i);const o=h.vec3();h.normalizeVec3(h.cross3Vec3(n,i,a),o),p[A]||(p[A]=[]),p[d]||(p[d]=[]),p[f]||(p[f]=[]),p[A].push(o),p[d].push(o),p[f].push(o)}for(o=o&&o.length===r.length?o:new Float32Array(r.length),c=0,u=p.length;c<u;c++){I=p[c].length,y=0,m=0,v=0;for(let e=0;e<I;e++)y+=p[c][e][0],m+=p[c][e][1],v+=p[c][e][2];o[3*c]=y/I,o[3*c+1]=m/I,o[3*c+2]=v/I}return o}})(),buildTangents:(()=>{const e=new r(3),t=new r(3),s=new r(3),n=new r(3),i=new r(3),a=new r(3),l=new r(3);return(r,o,c)=>{const u=new Float32Array(r.length);for(let p=0;p<o.length;p+=3){let A=o[p];const d=r.subarray(3*A,3*A+3),f=c.subarray(2*A,2*A+2);A=o[p+1];const I=r.subarray(3*A,3*A+3),y=c.subarray(2*A,2*A+2);A=o[p+2];const m=r.subarray(3*A,3*A+3),v=c.subarray(2*A,2*A+2),w=h.subVec3(I,d,e),g=h.subVec3(m,d,t),E=h.subVec2(y,f,s),T=h.subVec2(v,f,n),b=1/(E[0]*T[1]-E[1]*T[0]),D=h.mulVec3Scalar(h.subVec3(h.mulVec3Scalar(w,T[1],i),h.mulVec3Scalar(g,E[1],a),l),b,a);let P;for(let e=0;e<3;e++)P=3*o[p+e],u[P]+=D[0],u[P+1]+=D[1],u[P+2]+=D[2]}return u}})(),buildPickTriangles(e,t,s){const n=t.length,i=s?new Uint16Array(9*n):new Float32Array(9*n),a=new Uint8Array(12*n);let r,l,o,c,u,h,p=0,A=0,d=0;for(let s=0;s<n;s+=3)h=p>>24&255,u=p>>16&255,c=p>>8&255,o=255&p,l=t[s],r=3*l,i[A++]=e[r],i[A++]=e[r+1],i[A++]=e[r+2],a[d++]=o,a[d++]=c,a[d++]=u,a[d++]=h,l=t[s+1],r=3*l,i[A++]=e[r],i[A++]=e[r+1],i[A++]=e[r+2],a[d++]=o,a[d++]=c,a[d++]=u,a[d++]=h,l=t[s+2],r=3*l,i[A++]=e[r],i[A++]=e[r+1],i[A++]=e[r+2],a[d++]=o,a[d++]=c,a[d++]=u,a[d++]=h,p++;return{positions:i,colors:a}},faceToVertexNormals(e,t,s={}){const n=s.smoothNormalsAngleThreshold||20,i={},a=[],r={};let l,o,c,u,p;const A=1e4;let d,f,I,y,m,v;for(f=0,y=e.length;f<y;f+=3){d=f/3,o=e[f],c=e[f+1],u=e[f+2],p=`${Math.round(o*A)}_${Math.round(c*A)}_${Math.round(u*A)}`,void 0===i[p]?i[p]=[d]:i[p].push(d);const s=h.normalizeVec3([t[f],t[f+1],t[f+2]]);a[d]=s,l=h.vec4([s[0],s[1],s[2],1]),r[d]=l}for(p in i)if(i.hasOwnProperty(p)){const e=i[p],t=e.length;for(f=0;f<t;f++){const s=e[f];for(l=r[s],I=0;I<t;I++){if(f===I)continue;const t=e[I];m=a[s],v=a[t];Math.abs(h.angleVec3(m,v)/h.DEGTORAD)<n&&(l[0]+=v[0],l[1]+=v[1],l[2]+=v[2],l[3]+=1)}}}for(f=0,y=t.length;f<y;f+=3)l=r[f/3],t[f+0]=l[0]/l[3],t[f+1]=l[1]/l[3],t[f+2]=l[2]/l[3]},transformRay:(()=>{const e=new r(4),t=new r(4);return(s,n,i,a,r)=>{e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=1,h.transformVec4(s,e,t),a[0]=t[0],a[1]=t[1],a[2]=t[2],e[0]=i[0],e[1]=i[1],e[2]=i[2],h.transformVec3(s,e,t),h.normalizeVec3(t),r[0]=t[0],r[1]=t[1],r[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new r(16),t=new r(16),s=new r(4),n=new r(4),i=new r(4),a=new r(4);return(r,l,o,c,u,p)=>{const A=h.mulMat4(o,l,e),d=h.inverseMat4(A,t),f=r.width,I=r.height,y=(c[0]-f/2)/(f/2),m=-(c[1]-I/2)/(I/2);s[0]=y,s[1]=m,s[2]=-1,s[3]=1,h.transformVec4(d,s,n),h.mulVec4Scalar(n,1/n[3]),i[0]=y,i[1]=m,i[2]=1,i[3]=1,h.transformVec4(d,i,a),h.mulVec4Scalar(a,1/a[3]),u[0]=a[0],u[1]=a[1],u[2]=a[2],h.subVec3(a,n,p),h.normalizeVec3(p)}})(),canvasPosToLocalRay:(()=>{const e=new r(3),t=new r(3);return(s,n,i,a,r,l,o)=>{h.canvasPosToWorldRay(s,n,i,r,e,t),h.worldRayToLocalRay(a,e,t,l,o)}})(),worldRayToLocalRay:(()=>{const e=new r(16),t=new r(4),s=new r(4);return(n,i,a,r,l)=>{const o=h.inverseMat4(n,e);t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,h.transformVec4(o,t,s),r[0]=s[0],r[1]=s[1],r[2]=s[2],h.transformVec3(o,a,l)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(s,n,i,a){const l=new r(6),o={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:l};let c,u;for(l[0]=l[1]=l[2]=Number.POSITIVE_INFINITY,l[3]=l[4]=l[5]=Number.NEGATIVE_INFINITY,c=0,u=s.length;c<u;++c){var h=3*s[c];for(let e=0;e<3;++e){const t=3*n[h+e];i[t]<l[0]&&(l[0]=i[t]),i[t]>l[3]&&(l[3]=i[t]),i[t+1]<l[1]&&(l[1]=i[t+1]),i[t+1]>l[4]&&(l[4]=i[t+1]),i[t+2]<l[2]&&(l[2]=i[t+2]),i[t+2]>l[5]&&(l[5]=i[t+2])}}if(s.length<20||a>10)return o.triangles=s,o.leaf=!0,o;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];let p=0;e[1]>e[p]&&(p=1),e[2]>e[p]&&(p=2),o.splitDim=p;const A=(l[p]+l[p+3])/2,d=new Array(s.length);let f=0;const I=new Array(s.length);let y=0;for(c=0,u=s.length;c<u;++c){const e=n[h=3*s[c]],t=3*n[h+1],a=3*n[h+2];i[3*e+p]<=A||i[t+p]<=A||i[a+p]<=A?d[f++]=s[c]:I[y++]=s[c]}return d.length=f,I.length=y,o.left=t(d,n,i,a+1),o.right=t(I,n,i,a+1),o}return(e,s)=>{const n=e.length/3,i=new Array(n);for(let e=0;e<n;++e)i[e]=e;return t(i,e,s,0)}})(),decompressPosition(e,t,s){(s=s||e)[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[12],s[n+1]=e[n+1]*t[5]+t[13],s[n+2]=e[n+2]*t[10]+t[14];return s},decompressUV(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[6],s[n+1]=e[n+1]*t[4]+t[7];return s},octDecodeVec2(e,t){let s=e[0],n=e[1];s=(2*s+1)/255,n=(2*n+1)/255;const i=1-Math.abs(s)-Math.abs(n);i<0&&(s=(1-Math.abs(n))*(s>=0?1:-1),n=(1-Math.abs(s))*(n>=0?1:-1));const a=Math.sqrt(s*s+n*n+i*i);return t[0]=s/a,t[1]=n/a,t[2]=i/a,t},octDecodeVec2s(e,t){for(let s=0,n=0,i=e.length;s<i;s+=2){let i=e[s+0],a=e[s+1];i=(2*i+1)/255,a=(2*a+1)/255;const r=1-Math.abs(i)-Math.abs(a);r<0&&(i=(1-Math.abs(a))*(i>=0?1:-1),a=(1-Math.abs(i))*(a>=0?1:-1));const l=Math.sqrt(i*i+a*a+r*r);t[n+0]=i/l,t[n+1]=a/l,t[n+2]=r/l,n+=3}return t}};h.buildEdgeIndices=function(){const e=[],t=[],s=[],n=[],i=[];let a=0;const r=new Uint16Array(3),l=new Uint16Array(3),o=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3();return function(y,m,v,w){!function(i,a){const r={};let l,o,c,u;const h=Math.pow(10,4);let p,A,d=0;for(p=0,A=i.length;p<A;p+=3)l=i[p],o=i[p+1],c=i[p+2],u=Math.round(l*h)+"_"+Math.round(o*h)+"_"+Math.round(c*h),void 0===r[u]&&(r[u]=d/3,e[d++]=l,e[d++]=o,e[d++]=c),t[p/3]=r[u];for(p=0,A=a.length;p<A;p++)n[p]=t[a[p]],s[n[p]]=a[p]}(y,m),function(t,s){a=0;for(let y=0,m=t;y<m;y+=3){const t=3*n[y],m=3*n[y+1],v=3*n[y+2];s?(r[0]=e[t],r[1]=e[t+1],r[2]=e[t+2],l[0]=e[m],l[1]=e[m+1],l[2]=e[m+2],o[0]=e[v],o[1]=e[v+1],o[2]=e[v+2],h.decompressPosition(r,s,c),h.decompressPosition(l,s,u),h.decompressPosition(o,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[m],u[1]=e[m+1],u[2]=e[m+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,A),h.subVec3(c,u,d),h.cross3Vec3(A,d,f),h.normalizeVec3(f,I);const w=i[a]||(i[a]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],a++}}(m.length,v);const g=[],E=Math.cos(h.DEGTORAD*w),T={};let b,D,P,R,C,_,B,O,S,N,x,L=!1;for(let e=0,t=m.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=n[e+s],D=n[e+(s+1)%3],P=Math.min(b,D),R=Math.max(b,D),C=P+","+R,void 0===T[C]?T[C]={index1:P,index2:R,face1:t,face2:void 0}:T[C].face2=t}for(C in T)_=T[C],void 0!==_.face2&&(B=i[_.face1].normal,O=i[_.face2].normal,S=h.dotVec3(B,O),S>E)||(N=s[_.index1],x=s[_.index2],(!L&&N>65535||x>65535)&&(L=!0),g.push(N),g.push(x));return L?new Uint32Array(g):new Uint16Array(g)}}(),h.planeClipsPositions3=function(e,t,s,n=3){for(let i=0,a=s.length;i<a;i+=n){if(l[0]=s[i+0]-e[0],l[1]=s[i+1]-e[1],l[2]=s[i+2]-e[2],l[0]*t[0]+l[1]*t[1]+l[2]*t[2]<0)return!0}return!1};const p=new Float32Array(3);class A{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],s=e[0].charCodeAt(0),n=s+e[1],i=s;i<n;++i)t.push(i);return String.fromCharCode.apply(null,t)})).join("");function I(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return f.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const y=function(){for(var e={},t=window.location.search.substring(1).split("&"),s=0;s<t.length;s++){var n=t[s].split("=");if(void 0===e[n[0]])e[n[0]]=decodeURIComponent(n[1]);else if("string"==typeof e[n[0]]){var i=[e[n[0]],decodeURIComponent(n[1])];e[n[0]]=i}else e[n[0]].push(decodeURIComponent(n[1]))}return e}();const m={xmlToJson:function e(t,s){if(t.nodeType===t.TEXT_NODE){var n=t.nodeValue;if(null===n.match(/^\s+$/))return n}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var i={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var a=0;a<t.attributes.length;a++){var r=t.attributes[a];i[s[r.nodeName]||r.nodeName]=r.nodeValue}for(var l=0;l<t.childNodes.length;l++){(a=e(t.childNodes[l],s))&&i.children.push(a)}return i}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return I(t[0],2)+[1,4,7,10,13].map((function(e){return I((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var s=[],n=function(e){e.type===t&&s.push(e),(e.children||[]).forEach((function(e){n(e)}))};return n(e),s},timeout:function(e){return new Promise((function(t,s){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,s){var n=new XMLHttpRequest;n.open(e.method||"GET",e.url,!0),n.onload=function(e){4===n.readyState&&(200===n.status?t(n.responseXML):s(n.statusText))},n.send(null)}))},loadJSON:function(e,t,s){var n=e=>{};t=t||n,s=s||n;var i=new XMLHttpRequest;i.overrideMimeType("application/json"),i.open("GET",e,!0),i.addEventListener("load",(function(e){var n=e.target.response;if(200===this.status){var i;try{i=JSON.parse(n)}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(i)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(n))}catch(e){s(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else s(e)}),!1),i.addEventListener("error",(function(e){s(e)}),!1),i.send(null)},loadArraybuffer:function(e,t,s){var n=e=>{};t=t||n,s=s||n;const i=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(i){const e=!!i[2];var a=i[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),s=new Uint8Array(e);for(var r=0;r<a.length;r++)s[r]=a.charCodeAt(r);window.setTimeout((function(){t(e)}),0)}catch(e){window.setTimeout((function(){s(e)}),0)}}else{const n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onreadystatechange=function(){4===n.readyState&&(200===n.status?t(n.response):s("loadArrayBuffer error : "+n.response))},n.send(null)}},queryString:y,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return m.isString(e)||m.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(m.isNumeric(e)||m.isString(e)?`${e}`:e.id)===(m.isNumeric(t)||m.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return m.apply(e,{})},apply:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(t[s]=e[s]);return t},apply2:function(e,t){for(const s in e)e.hasOwnProperty(s)&&void 0!==e[s]&&null!==e[s]&&(t[s]=e[s]);return t},applyIf:function(e,t){for(const s in e)e.hasOwnProperty(s)&&(void 0!==t[s]&&null!==t[s]||(t[s]=e[s]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return m.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const s=new e.constructor(e.length+t.length);return s.set(e),s.set(t,e.length),s},flattenParentChildHierarchy:function(e){var t=[];return function e(s){s.id=s.uuid,delete s.oid,t.push(s);var n=s.children;if(n)for(var i=0,a=n.length;i<a;i++){n[i].parent=s.id,e(n[i])}s.children=[]}(e),t}},v={},w=new e,g=new A,E={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},T=[];let b,D=0,P=0;const R=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(R.scenes[e.id])return void console.error(`[ERROR] Scene ${m.inQuotes(e.id)} already exists`)}else e.id=w.addItem({});R.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,s=e.ticksPerRender;v[e.id]={ticksPerOcclusionTest:t,ticksPerRender:s,renderCountdown:s},d.components.scenes++,e.once("destroyed",(()=>{w.removeItem(e.id),delete R.scenes[e.id],delete v[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in R.scenes)R.scenes.hasOwnProperty(t)&&(e=R.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete R.scenes[e.id]))},this.scheduleTask=function(e,t){g.push(e),g.push(t)},this.runTasks=function(e=-1){let t,s,n=(new Date).getTime(),i=0;for(;g.length>0&&(e<0||n<e);)t=g.shift(),s=g.shift(),s?t.call(s):t(),n=(new Date).getTime(),i++;return i},this.getNumTasks=function(){return g.length}},C=function(){let e=Date.now();if(b=e-D,D>0&&b>0){var t=1e3/b;P+=t,T.push(t),T.length>=30&&(P-=T.shift()),d.frame.fps=Math.round(P/T.length)}!function(e){const t=R.runTasks(e+10),s=R.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=s,d.frame.tasksBudget=10}(e),function(e){for(var t in E.time=e,R.scenes)if(R.scenes.hasOwnProperty(t)){var s=R.scenes[t];E.sceneId=t,E.startTime=s.startTime,E.deltaTime=null!=E.prevTime?E.time-E.prevTime:0,s.fire("tick",E,!0)}E.prevTime=e}(e),function(){const e=R.scenes,t=!1;let s,n,i,a,r;for(r in e)e.hasOwnProperty(r)&&(s=e[r],n=v[r],n||(n=v[r]={}),i=s.ticksPerOcclusionTest,n.ticksPerOcclusionTest!==i&&(n.ticksPerOcclusionTest=i,n.renderCountdown=i),--s.occlusionTestCountdown<=0&&(s.doOcclusionTest(),s.occlusionTestCountdown=i),a=s.ticksPerRender,n.ticksPerRender!==a&&(n.ticksPerRender=a,n.renderCountdown=a),0==--n.renderCountdown&&(s.render(t),n.renderCountdown=a))}(),D=e,void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C)};void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(C):requestAnimationFrame(C);class _{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof _))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];let i;if(n)for(const s in n)n.hasOwnProperty(s)&&(i=n[s],this._eventCallDepth++,this._eventCallDepth<300?i.callback.call(i.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let i=this._eventSubs[t];i?this._eventSubsNum[t]++:(i={},this._eventSubs[t]=i,this._eventSubsNum[t]=1);const a=this._subIdMap.addItem();i[a]={callback:s,scope:n||this},this._subIdEvents[a]=t;const r=this._events[t];return void 0!==r&&s.call(n||this,r),a}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const n=this,i=this.on(e,(function(e){n.off(i),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+m.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let s=e.component;const n=e.sceneDefault,i=e.sceneSingleton,a=e.type,r=e.on,l=!1!==e.recompiles;if(s&&(m.isNumeric(s)||m.isString(s))){const e=s;if(s=this.scene.components[e],!s)return void this.error("Component not found: "+m.inQuotes(e))}if(!s)if(!0===i){const e=this.scene.types[a];for(const t in e)if(e.hasOwnProperty){s=e[t];break}if(!s)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===n&&(s=this.scene[t],!s))return this.error("Scene has no default component for '"+t+"'"),null;if(s){if(s.scene.id!==this.scene.id)return void this.error("Not in same scene: "+s.type+" "+m.inQuotes(s.id));if(a&&!s.isType(a))return void this.error("Expected a "+a+" type or subtype: "+s.type+" "+m.inQuotes(s.id))}this._attachments||(this._attachments={});const o=this._attached[t];let c,u,h;if(o){if(s&&o.id===s.id)return;const e=this._attachments[o.id];for(c=e.subs,u=0,h=c.length;u<h;u++)o.off(c[u]);delete this._attached[t],delete this._attachments[o.id];const n=e.params.onDetached;n&&(m.isFunction(n)?n(o):n.scope?n.callback.call(n.scope,o):n.callback(o)),e.managingLifecycle&&o.destroy()}if(s){const n={params:e,component:s,subs:[],managingLifecycle:false};n.subs.push(s.once("destroyed",(function(){n.params.component=null,this._attach(n.params)}),this)),l&&n.subs.push(s.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=s,this._attachments[s.id]=n;const i=e.onAttached;if(i&&(m.isFunction(i)?i(s):i.scope?i.callback.call(i.scope,s):i.callback(s)),r){let e,t,i,a;for(e in r)if(r.hasOwnProperty(e)){if(t=r[e],m.isFunction(t)?(i=t,a=null):(i=t.callback,a=t.scope),!i)continue;n.subs.push(s.on(e,i,a))}}}return l&&this.fire("dirty",this),this.fire(t,s),s}_checkComponent(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!m.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var s=0,n=e.length;s<n;s++)if(e[s]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():R.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,s,n,i,a;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],s=t.component,n=t.subs,i=0,a=n.length;i<a;i++)s.off(n[i]);t.managingLifecycle&&s.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(s=this._ownedComponents[e],s.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const B=h.vec3(),O=h.vec3(),S=h.mat4();class N{constructor(){this.normal=h.vec3(),this.offset=0,this.testVertex=h.vec3()}set(e,t,s,n){const i=1/Math.sqrt(e*e+t*t+s*s);this.normal[0]=e*i,this.normal[1]=t*i,this.normal[2]=s*i,this.offset=n*i,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class x{constructor(){this.planes=[new N,new N,new N,new N,new N,new N]}}function L(e,t,s){const n=h.mulMat4(s,t,S),i=n[0],a=n[1],r=n[2],l=n[3],o=n[4],c=n[5],u=n[6],p=n[7],A=n[8],d=n[9],f=n[10],I=n[11],y=n[12],m=n[13],v=n[14],w=n[15];e.planes[0].set(l-i,p-o,I-A,w-y),e.planes[1].set(l+i,p+o,I+A,w+y),e.planes[2].set(l-a,p-c,I-d,w-m),e.planes[3].set(l+a,p+c,I+d,w+m),e.planes[4].set(l-r,p-u,I-f,w-v),e.planes[5].set(l+r,p+u,I+f,w+v)}function M(e,t){let s=x.INSIDE;const n=B,i=O;n[0]=t[0],n[1]=t[1],n[2]=t[2],i[0]=t[3],i[1]=t[4],i[2]=t[5];const a=[n,i];for(let t=0;t<6;++t){const n=e.planes[t];if(n.normal[0]*a[n.testVertex[0]][0]+n.normal[1]*a[n.testVertex[1]][1]+n.normal[2]*a[n.testVertex[2]][2]+n.offset<0)return x.OUTSIDE;n.normal[0]*a[1-n.testVertex[0]][0]+n.normal[1]*a[1-n.testVertex[1]][1]+n.normal[2]*a[1-n.testVertex[2]][2]+n.offset<0&&(s=x.INTERSECT)}return s}x.INSIDE=0,x.INTERSECT=1,x.OUTSIDE=2;class F extends _{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=h.vec2(),this._canvasMarqueeCorner2=h.vec2(),this._canvasMarquee=h.AABB2(),this._marqueeFrustum=new x,this._marqueeFrustumProjMat=h.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==F.PICK_MODE_INSIDE&&e!==F.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===F.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(s,n=x.INTERSECT)=>{if(n===x.INTERSECT&&(n=M(this._marqueeFrustum,s.aabb)),n!==x.OUTSIDE){if(s.entities){const t=s.entities;for(let s=0,n=t.length;s<n;s++){const n=t[s];if(!n.visible)continue;const i=n.aabb;if(this._pickMode===F.PICK_MODE_INSIDE){M(this._marqueeFrustum,i)===x.INSIDE&&e.push(n.id)}else{M(this._marqueeFrustum,i)!==x.OUTSIDE&&e.push(n.id)}}}s.left&&t(s.left,n),s.right&&t(s.right,n)}};return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,s=e.clientHeight,n=e.clientLeft,i=e.clientTop,a=2/t,r=2/s,l=e.clientHeight/e.clientWidth,o=(this._canvasMarquee[0]-n)*a-1,c=(this._canvasMarquee[2]-n)*a-1,u=-(this._canvasMarquee[3]-i)*r+1,p=-(this._canvasMarquee[1]-i)*r+1,A=this.viewer.scene.camera.frustum.near*(17*l);h.frustumMat4(o,c,u*l,p*l,A,1e4,this._marqueeFrustumProjMat),L(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}F.PICK_MODE_INTERSECTS=0,F.PICK_MODE_INSIDE=1;class H{constructor(e,t,s){this.id=s&&s.id?s.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];let i;if(n)for(const s in n)n.hasOwnProperty(s)&&(i=n[s],this._eventCallDepth++,this._eventCallDepth<300?i.callback.call(i.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,s,n){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let i=this._eventSubs[t];i?this._eventSubsNum[t]++:(i={},this._eventSubs[t]=i,this._eventSubsNum[t]=1);const a=this._subIdMap.addItem();i[a]={callback:s,scope:n||this},this._subIdEvents[a]=t;const r=this._events[t];return void 0!==r&&s.call(n||this,r),a}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const s=this._eventSubs[t];s&&(delete s[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,s){const n=this,i=this.on(e,(function(e){n.off(i),t.call(s||this,e)}),s)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const U=h.vec3(),G=function(){const e=new Float64Array(16),t=new Float64Array(4),s=new Float64Array(4);return function(n,i,a){return a=a||e,t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=1,h.transformVec4(n,t,s),h.setMat4Translation(n,s,a),a.slice()}}();function j(e,t,s){const n=Float32Array.from([e[0]])[0],i=e[0]-n,a=Float32Array.from([e[1]])[0],r=e[1]-a,l=Float32Array.from([e[2]])[0],o=e[2]-l;t[0]=n,t[1]=a,t[2]=l,s[0]=i,s[1]=r,s[2]=o}function V(e,t,s,n=1e3){const i=h.getPositionsCenter(e,U),a=Math.round(i[0]/n)*n,r=Math.round(i[1]/n)*n,l=Math.round(i[2]/n)*n;s[0]=a,s[1]=r,s[2]=l;const o=0!==s[0]||0!==s[1]||0!==s[2];if(o)for(let s=0,n=e.length;s<n;s+=3)t[s+0]=e[s+0]-a,t[s+1]=e[s+1]-r,t[s+2]=e[s+2]-l;return o}function k(e,t,s,n){const i=h.dotVec3(t,s)+e,a=h.normalizeVec3(t,U);return h.mulVec3Scalar(a,-i,n),n}const Q=1,W=4,z=8,K=16,Y=32,X=256,q=512,J=1024,Z=2048,$=new Float32Array([0,0,0]),ee=new Uint16Array([0,0,0]);h.OBB3();class te{constructor(e,t,s,n,i,a,r){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=n,this._numPrimitives=0;for(let e=0,t=this.meshes.length;e<t;e++){const t=this.meshes[e];t.parent=this,t.entity=this,this._numPrimitives+=t.numPrimitives}this.id=s,this.originalSystemId=h.unglobalizeObjectId(e.id,s),this._flags=i,this._aabb=a,this._worldAABB=h.AABB3(a),this._offsetAABB=h.AABB3(a),this._aabbDirty=!0,this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!r,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}_transformDirty(){this._aabbDirty=!0,this.model._transformDirty()}_sceneModelDirty(){this._aabbDirty=!0;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._sceneModelDirty()}get aabb(){if(this._aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this.meshes.length;e<t;e++)h.expandAABB3(this._aabb,this.meshes[e].aabb);this._aabbDirty=!1}return this._aabb}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get numPrimitives(){return this._numPrimitives}get numTriangles(){return this._numPrimitives}get visible(){return this._getFlag(Q)}set visible(e){if(!!(this._flags&Q)!==e){this._flags=e?this._flags|Q:this._flags&~Q;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}get highlighted(){return this._getFlag(q)}set highlighted(e){if(!!(this._flags&q)!==e){this._flags=e?this._flags|q:this._flags&~q;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(X)}set xrayed(e){if(!!(this._flags&X)!==e){this._flags=e?this._flags|X:this._flags&~X;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}get selected(){return this._getFlag(J)}set selected(e){if(!!(this._flags&J)!==e){this._flags=e?this._flags|J:this._flags&~J;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}get edges(){return this._getFlag(Z)}set edges(e){if(!!(this._flags&Z)!==e){this._flags=e?this._flags|Z:this._flags&~Z;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this._setCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this._setCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this._setCulled()}_setCulled(){let e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&W)!==e){this._flags=e?this._flags|W:this._flags&~W;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(K)}set clippable(e){if(!!(this._flags&K)!==e){this._flags=e?this._flags|K:this._flags&~K;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(Y)}set collidable(e){if(!!(this._flags&Y)!==e){this._flags=e?this._flags|Y:this._flags&~Y;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(z)}set pickable(e){if(!!(this._flags&z)!==e){this._flags=e?this._flags|z:this._flags&~z;for(var t=0,s=this.meshes.length;t<s;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return $[0]=e[0]/255,$[1]=e[1]/255,$[2]=e[2]/255,$}set colorize(e){if(e){ee[0]=Math.floor(255*e[0]),ee[1]=Math.floor(255*e[1]),ee[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(ee)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,s=this.meshes[0]._colorize[3];let n=255;if(t){if(e<0?e=0:e>1&&(e=1),n=Math.floor(255*e),s===n)return}else if(n=255,s===n)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(n,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._aabbDirty=!0,this.model._aabbDirty=!0,this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model.glRedraw()}get saoEnabled(){return this.model.saoEnabled}getEachVertex(e){for(let t=0,s=this.meshes.length;t<s;t++)this.meshes[t].getEachVertex(e)}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this._opacityUpdated&&this.scene._objectColorizeUpdated(this,!1),this._opacityUpdated&&this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const se=h.vec4(),ne=h.vec4();class ie extends _{constructor(e,t){super(e,t),this._entity=null,this._visible=null,this._worldPos=h.vec3(),this._origin=h.vec3(),this._rtcPos=h.vec3(),this._viewPos=h.vec3(),this._canvasPos=h.vec2(),this._occludable=!1,this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(h.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){se.set(this._viewPos),se[3]=1,h.transformPoint4(this.scene.camera.projMatrix,se,ne);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ne[0]/ne[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ne[1]/ne[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof te?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e)}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),j(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}class ae{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,n=s.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var i=this._wireClickable,a=i.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=0,a["pointer-events"]="none",t.onContextMenu,e.appendChild(i),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,s=this._wire.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)";var n=this._wireClickable.style;n.width=Math.round(e)+"px",n.left=Math.round(this._x1)+"px",n.top=Math.round(this._y1)+"px",n["-webkit-transform"]="rotate("+t+"deg)",n["-moz-transform"]="rotate("+t+"deg)",n["-ms-transform"]="rotate("+t+"deg)",n["-o-transform"]="rotate("+t+"deg)",n.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,s,n){this._x1=e,this._y1=t,this._x2=s,this._y2=n,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class re{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._visible=!0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!0,this._culled=!1;var s=this._dot,n=s.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==t.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",t.onContextMenu,e.appendChild(s);var i=this._dotClickable,a=i.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",t.onContextMenu,e.appendChild(i),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&i.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var s=this._dot.style;s.left=Math.round(e)-4+"px",s.top=Math.round(t)-4+"px";var n=this._dotClickable.style;n.left=Math.round(e)-9+"px",n.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class le{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label";var s=this._label,n=s.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,t.onContextMenu,s.innerText="",e.appendChild(s),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&s.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&s.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&s.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onContextMenu&&s.addEventListener("contextmenu",(e=>{t.onContextMenu(e,this),e.preventDefault()}))}setPos(e,t){this._x=e,this._y=t;var s=this._label.style;s.left=Math.round(e)-20+"px",s.top=Math.round(t)-12+"px"}setPosOnWire(e,t,s,n){var i=e+.5*(s-e),a=t+.5*(n-t),r=this._label.style;r.left=Math.round(i)-20+"px",r.top=Math.round(a)-12+"px"}setPosBetweenWires(e,t,s,n,i,a){var r=(e+s+i)/3,l=(t+n+a)/3,o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(l)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var oe=h.vec3(),ce=h.vec3();class ue extends _{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._cornerMarker=new ie(s,t.corner),this._targetMarker=new ie(s,t.target),this._originWorld=h.vec3(),this._cornerWorld=h.vec3(),this._targetWorld=h.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._cornerDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._originWire=new ae(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetWire=new ae(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._angleLabel=new le(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const A=-.3,d=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],I=this._targetMarker.viewPos[2];if(d>A||f>A||I>A)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,s=this._cp,n=e.canvas.canvas.getBoundingClientRect();const y=this._container.getBoundingClientRect();for(var i=n.top-y.top,a=n.left-y.left,r=e.canvas.boundary,l=r[2],o=r[3],c=0,u=0,p=t.length;u<p;u+=4)s[c]=a+Math.floor((1+t[u+0]/t[u+3])*l/2),s[c+1]=i+Math.floor((1-t[u+1]/t[u+3])*o/2),c+=2;if(this._originDot.setPos(s[0],s[1]),this._cornerDot.setPos(s[2],s[3]),this._targetDot.setPos(s[4],s[5]),this._originWire.setStartAndEnd(s[0],s[1],s[2],s[3]),this._targetWire.setStartAndEnd(s[2],s[3],s[4],s[5]),this._angleLabel.setPosBetweenWires(s[0],s[1],s[2],s[3],s[4],s[5]),h.subVec3(this._originWorld,this._cornerWorld,oe),h.subVec3(this._targetWorld,this._cornerWorld,ce),!(0===oe[0]&&0===oe[1]&&0===oe[2]||0===ce[0]&&0===ce[1]&&0===ce[2])){const e=this._approximate?" ~ ":" = ";h.normalizeVec3(oe),h.normalizeVec3(ce);const t=Math.abs(h.angleVec3(oe,ce));this._angle=t/h.DEGTORAD,this._angleLabel.setText(e+this._angle.toFixed(2)+"°")}else this._angleLabel.setText("");this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setCulled(!(this._visible&&this._angleVisible&&this.labelsVisible)),this._cpDirty=!1}}_isSliced(e){const t=this.scene._sectionPlanesState.sectionPlanes;for(let s=0,n=t.length;s<n;s++){const n=t[s];if(h.planeClipsPositions3(n.pos,n.dir,e,4))return!0}return!1}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get corner(){return this._cornerMarker}get target(){return this._targetMarker}get angle(){return this._update(),this._angle}get color(){return this._color}set color(e){this._originDot.setFillColor(e),this._cornerDot.setFillColor(e),this._targetDot.setFillColor(e),this._originWire.setColor(e||"blue"),this._targetWire.setColor(e||"red"),this._angleLabel.setFillColor(e||"#00BBFF"),this._color=e}set visible(e){e=!1!==e,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._originWire.setVisible(this._visible&&this._originWireVisible),this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=!1!==e,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._cpDirty=!0,this._needUpdate()}get originVisible(){return this._originVisible}set cornerVisible(e){e=!1!==e,this._cornerVisible=e,this._cornerDot.setVisible(this._visible&&this._cornerVisible),this._cpDirty=!0,this._needUpdate()}get cornerVisible(){return this._cornerVisible}set targetVisible(e){e=!1!==e,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible),this._cpDirty=!0,this._needUpdate()}get targetVisible(){return this._targetVisible}set originWireVisible(e){e=!1!==e,this._originWireVisible=e,this._originWire.setVisible(this._visible&&this._originWireVisible),this._cpDirty=!0,this._needUpdate()}get originWireVisible(){return this._originWireVisible}set targetWireVisible(e){e=!1!==e,this._targetWireVisible=e,this._targetWire.setVisible(this._visible&&this._targetWireVisible),this._cpDirty=!0,this._needUpdate()}get targetWireVisible(){return this._targetWireVisible}set angleVisible(e){e=!1!==e,this._angleVisible=e,this._angleLabel.setVisible(this._visible&&this._angleVisible),this._cpDirty=!0,this._needUpdate()}get angleVisible(){return this._angleVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._angleLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._cornerDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._originWire.setHighlighted(e),this._targetWire.setHighlighted(e),this._angleLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._cornerDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._originWire.setClickable(this._clickable),this._targetWire.setClickable(this._clickable),this._angleLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onSectionPlaneUpdated&&e.off(this._onSectionPlaneUpdated),this._originDot.destroy(),this._cornerDot.destroy(),this._targetDot.destroy(),this._originWire.destroy(),this._targetWire.destroy(),this._angleLabel.destroy(),super.destroy()}}class he extends _{get active(){}set snapping(e){}get snapping(){return!0}activate(){}deactivate(){}reset(){}destroy(){}}class pe extends he{constructor(e,t={}){super(e.viewer.scene),this.pointerLens=t.pointerLens,this._active=!1,this._mouseState=0,this._currentAngleMeasurement=null;const s=document.createElement("div"),n=this.scene.canvas.canvas;n.parentNode.insertBefore(s,n),s.style.background="black",s.style.border="2px solid blue",s.style.borderRadius="10px",s.style.width="5px",s.style.height="5px",s.style.margin="-200px -200px",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",this.markerDiv=s,this._onMouseHoverSurface=null,this._onHoverNothing=null,this._onPickedNothing=null,this._onPickedSurface=null,this._onInputMouseDown=null,this._onInputMouseUp=null,this._snapping=!1!==t.snapping,this._attachPlugin(e,t)}_attachPlugin(e,t={}){this.angleMeasurementsPlugin=e,this.plugin=e}get active(){return this._active}set snapping(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}get snapping(){return this._snapping}activate(){if(this._active)return;this.angleMeasurementsPlugin;const e=this.scene;e.input;const t=e.canvas.canvas,s=this.angleMeasurementsPlugin.viewer.cameraControl,n=this.pointerLens;let i=!1,a=!1,r=0,l=0;const o=h.vec3(),c=h.vec2();this._currentAngleMeasurement=null,this._onMouseHoverSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(n&&(n.visible=!0,n.canvasPos=e.canvasPos,n.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,n.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(n&&(n.visible=!0,n.canvasPos=e.canvasPos,n.snappedCanvasPos=e.canvasPos,n.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const s=e.snappedCanvasPos||e.canvasPos;switch(i=!0,a=e.entity,o.set(e.worldPos),c.set(s),this._mouseState){case 0:this.markerDiv.style.marginLeft=s[0]-5+"px",this.markerDiv.style.marginTop=s[1]-5+"px";break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos),this.markerDiv.style.marginLeft="-10000px",this.markerDiv.style.marginTop="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(r=e.clientX,l=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>r+20||e.clientX<r-20||e.clientY>l+20||e.clientY<l-20))switch(this._mouseState){case 0:i&&(this._currentAngleMeasurement=this.angleMeasurementsPlugin.createMeasurement({id:h.createUUID(),origin:{entity:a,worldPos:o},corner:{entity:a,worldPos:o},target:{entity:a,worldPos:o},approximate:!0}),this._currentAngleMeasurement.clickable=!1,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.angleVisible=!1,this._mouseState=1,this.angleMeasurementsPlugin.fire("measurementStart",this._currentAngleMeasurement));break;case 1:i?(this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._mouseState=2):this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._mouseState=0,this.angleMeasurementsPlugin.fire("measurementCancel",this._currentAngleMeasurement));break;case 2:i?(this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.clickable=!0,this.angleMeasurementsPlugin.fire("measurementEnd",this._currentAngleMeasurement),this._currentAngleMeasurement=null,this._mouseState=0):this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null,this._mouseState=0,this.angleMeasurementsPlugin.fire("measurementCancel",this._currentAngleMeasurement))}}),this._onMouseHoverOff=s.on(this._snapping?"hoverSnapOrSurfaceOff":"hoverOff",(e=>{if(i=!1,n&&(n.visible=!0,n.pointerPos=e.canvasPos,n.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,n.snapped=!1),this.markerDiv.style.marginLeft="-100px",this.markerDiv.style.marginTop="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}destroy(){this.deactivate(),super.destroy()}}class Ae extends ie{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._marker=t.firstChild,this._container.appendChild(this._marker),this._marker.style.visibility=this._markerShown?"visible":"hidden",this._marker.addEventListener("click",(()=>{this.plugin.fire("markerClicked",this)})),this._marker.addEventListener("mouseenter",(()=>{this.plugin.fire("markerMouseEnter",this)})),this._marker.addEventListener("mouseleave",(()=>{this.plugin.fire("markerMouseLeave",this)})),this._marker.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}if(!this._labelExternal){this._label&&(this._container.removeChild(this._label),this._label=null);let e=this._labelHTML||"<p></p>";m.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e);const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],s=e[1],n=this.canvasPos;this._marker.style.left=Math.floor(t+n[0])-12+"px",this._marker.style.top=Math.floor(s+n[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+n[0]+20)+"px",this._label.style.top=Math.floor(s+n[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const s=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),s)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const s=e[t];this.setField(t,s)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):this._marker.parentNode.removeChild(this._marker)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const de=h.vec3(),fe=h.vec3(),Ie=h.vec3();class ye extends _{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,s=t.style;s.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",s.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const s=this._element;s&&(s.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const me=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class ve extends _{constructor(e,t={}){super(e,t),this._backgroundColor=h.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const s=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),s.scene._webglContextLost(),s.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){s._initWebGL(),s.gl&&(s.scene._webglContextRestored(s.gl),s.fire("webglcontextrestored",s.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let n=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(n=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{n&&(n=!1,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary[0]=s.canvas.offsetLeft,s.boundary[1]=s.canvas.offsetTop,s.boundary[2]=s.canvas.clientWidth,s.boundary[3]=s.canvas.clientHeight,s.fire("boundary",s.boundary))})),this._spinner=new ye(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+h.createUUID(),t=document.getElementsByTagName("body")[0],s=document.createElement("div"),n=s.style;n.height="100%",n.width="100%",n.padding="0",n.margin="0",n.background="rgba(0,0,0,0);",n.float="left",n.left="0",n.top="0",n.position="absolute",n.opacity="1.0",n["z-index"]="-10000",s.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(s),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,s=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:s}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<me.length;e++)try{this.gl=this.canvas.getContext(me[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));{const e=this.gl;let t="__",s=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,s.call(this,e))};let n={},i=e.bindTexture;e.bindTexture=function(e,s){n[t]!==s&&(n[t]=s,i.call(this,e,s))}}this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,s,n){return this.scene._renderer.readPixels(e,t,s,n)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class we{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.pickElementsCount=null,this.pickElementsOffset=null,this.lineWidth=1,this.snapPickLayerParams={},this.snapPickLayerNumber=0,this.snapPickCoordinateScale=h.vec3(),this.snapPickOrigin=h.vec3()}getRTCViewMatrix(e,t){let s=this._rtcViewMats[e];return s||(s=this._getNewMat(),G(this._scene.camera.viewMatrix,t,s),this._rtcViewMats[e]=s),s}getRTCPickViewMatrix(e,t){let s=this._rtcPickViewMats[e];if(!s){s=this._getNewMat();const n=this.pickViewMatrix||this._scene.camera.viewMatrix;G(n,t,s),this._rtcPickViewMats[e]=s}return s}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=h.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}const ge={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},Ee=document.createElement("canvas");if(Ee){const e=Ee.getContext("webgl",{antialias:!0})||Ee.getContext("experimental-webgl",{antialias:!0});ge.WEBGL=!!e,ge.WEBGL&&(ge.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?ge.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?ge.FS_MAX_FLOAT_PRECISION="mediump":ge.FS_MAX_FLOAT_PRECISION="lowp":ge.FS_MAX_FLOAT_PRECISION="mediump",ge.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),ge.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),ge.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),ge.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),ge.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ge.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),ge.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),ge.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),ge.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),ge.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){ge.SUPPORTED_EXTENSIONS[e]=!0})))}class Te{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class be{constructor(e,t,s){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,s),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=s.split("\n"),n=[];for(let e=0;e<t.length;e++)n.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(n.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class De{constructor(e,t){this.bindTexture=function(s,n){return!!s.bind(n)&&(e.uniform1i(t,n),!0)}}}class Pe{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const Re=new e({});function Ce(e){const t=[];let s,n;for(let i=0,a=e.length;i<a;i++)s=e[i],n=s.indexOf("/"),n>0&&"/"===s.charAt(n+1)&&(s=s.substring(0,n)),t.push(s);return t.join("\n")}function _e(e){console.error(e.join("\n"))}class Be{constructor(e,t){this.id=Re.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new be(e,e.VERTEX_SHADER,Ce(this.source.vertex)),this._fragmentShader=new be(e,e.FRAGMENT_SHADER,Ce(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void _e(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void _e(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void _e(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void _e(this.errors);let t,s,n,i,a;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void _e(this.errors);const r=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(s=0;s<r;++s)n=e.getActiveUniform(this.handle,s),n&&(i=n.name,"\0"===i[i.length-1]&&(i=i.substr(0,i.length-1)),a=e.getUniformLocation(this.handle,i),n.type===e.SAMPLER_2D||n.type===e.SAMPLER_CUBE||35682===n.type||e instanceof WebGL2RenderingContext&&(n.type===e.UNSIGNED_INT_SAMPLER_2D||n.type===e.INT_SAMPLER_2D)?this.samplers[i]=new De(e,a):this.uniforms[i]=a);const l=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(s=0;s<l;s++)t=e.getActiveAttrib(this.handle,s),t&&(a=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new Pe(e,a));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,s){if(!this.allocated)return!1;const n=this.samplers[e];return!!n&&n.bindTexture(t,s)}destroy(){this.allocated&&(Re.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}class Oe{constructor(e,t,s,n,i,a,r,l,o){switch(this._gl=e,this.type=t,this.allocated=!1,s.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=a,this.length=0,this.dataLength=n,this.numItems=0,this.itemSize=i,this.normalized=!!r,this.stride=l||0,this.offset=o||0,this._allocate(s)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Se{constructor(e,t){this.scene=e,this.aabb=h.AABB3(),this.origin=h.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const s=this.markerList[t].worldPos;this.positions[e++]=s[0],this.positions[e++]=s[1],this.positions[e++]=s[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;h.collapseAABB3(e),h.expandAABB3Points3(e,this.positions);const t=this.origin;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,s=this.numMarkers;this.positionsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),s,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,s=e.boundary,n=s[2],i=s[3];let a=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const s=this.markerList[e];if(s.viewPos[2]>-t){s._setVisible(!1);continue}const r=s.canvasPos,l=r[0],o=r[1];l+10<0||o+10<0||l-10>n||o-10>i?s._setVisible(!1):!s.entity||s.entity.visible?s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[a++]=l,this.pixels[a++]=o):s._setVisible(!0):s._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s];if(t.active){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const n=0===e;this.sectionPlanesActive[s]=n}else this.sectionPlanesActive[s]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const Ne=h.vec3([1,0,0]),xe=h.vec3();class Le{constructor(e,t){this._scene=e,this._renderBufferManager=t,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s||(s=new Se(this._scene,e.origin),this._occlusionLayers[s.originHash]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const s=e.origin.join();if(s!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let n=this._occlusionLayers[s];n||(n=new Se(this._scene,e.origin),this._occlusionLayers[s]=t,this._occlusionLayersListDirty=!0),n.addMarker(e),this._markersToOcclusionLayersMap[e.id]=n}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let s=this._occlusionLayers[t];s&&(1===s.numMarkers?(s.destroy(),delete this._occlusionLayers[s.originHash],this._occlusionLayersListDirty=!0):s.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._readPixelBuf=this._renderBufferManager.getRenderBuffer("occlusionReadPix"),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// OcclusionTester vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 worldPosition = vec4(position, 1.0); "),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&s.push(" vWorldPosition = worldPosition;"),s.push(" vec4 clipPos = projMatrix * viewPosition;"),s.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?s.push("vFragDepth = 1.0 + clipPos.w;"):s.push("clipPos.z += -0.001;"),s.push(" gl_Position = clipPos;"),s.push("}"),s}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// OcclusionTester fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),n.push("}"),n}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,s=e._sectionPlanesState;if(this._program=new Be(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,s=this._program,n=e._sectionPlanesState,i=e.camera,a=e.camera.project;if(s.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,s=this._occlusionLayersList.length;e<s;e++){const s=this._occlusionLayersList[e];if(s.update(),s.culledBySectionPlanes)continue;const a=s.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,G(i.viewMatrix,a));const r=n.sectionPlanes.length;if(r>0){const e=n.sectionPlanes;for(let n=0;n<r;n++){const i=this._uSectionPlanes[n];if(i){const r=s.sectionPlanesActive[n];if(t.uniform1i(i.active,r?1:0),r){const s=e[n];t.uniform3fv(i.pos,k(s.dist,s.dir,a,xe)),t.uniform3fv(i.dir,s.dir)}}}}this._aPosition.bindArrayBuffer(s.positionsBuf);const l=s.indicesBuf;l.bind(),t.drawElements(t.POINTS,l.numItems,l.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*Ne[0],s=255*Ne[1],n=255*Ne[2];for(let i=0,a=this._occlusionLayersList.length;i<a;i++){const a=this._occlusionLayersList[i];for(let i=0;i<a.lenOcclusionTestList;i++){const r=a.occlusionTestList[i],l=2*i,o=this._readPixelBuf.read(Math.round(a.pixels[l]*e),Math.round(a.pixels[l+1]*e)),c=o[0]===t&&o[1]===s&&o[2]===n;r._setVisible(c)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].destroy()}this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const Me=h.vec2();class Fe{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(n.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,s=this._program,n=this._scene,i=n.sao,a=t.drawingBufferWidth,r=t.drawingBufferHeight,l=n.camera.project._state,o=l.near,c=l.far,u=l.matrix,p=this._getInverseProjectMat(),A=Math.random(),d="perspective"===n.camera.projection;Me[0]=a,Me[1]=r,t.viewport(0,0,a,r),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),s.bind(),t.uniform1f(this._uCameraNear,o),t.uniform1f(this._uCameraFar,c),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,u),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,p),t.uniform1i(this._uPerspective,d),t.uniform1f(this._uScale,i.scale*(c/5)),t.uniform1f(this._uIntensity,i.intensity),t.uniform1f(this._uBias,i.bias),t.uniform1f(this._uKernelRadius,i.kernelRadius),t.uniform1f(this._uMinResolution,i.minResolution),t.uniform2fv(this._uViewport,Me),t.uniform1f(this._uRandomSeed,A);const f=e.getDepthTexture();s.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const s=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Be(s,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const n=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),a=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(s,s.ARRAY_BUFFER,i,i.length,3,s.STATIC_DRAW),this._uvBuf=new Oe(s,s.ARRAY_BUFFER,n,n.length,2,s.STATIC_DRAW),this._indicesBuf=new Oe(s,s.ELEMENT_ARRAY_BUFFER,a,a.length,1,s.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const He=new Float32Array(Qe(17,[0,1])),Ue=new Float32Array(Qe(17,[1,0])),Ge=new Float32Array(function(e,t){const s=[];for(let n=0;n<=e;n++)s.push(ke(n,t));return s}(17,4)),je=new Float32Array(2);class Ve{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Be(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Oe(e,e.ARRAY_BUFFER,s,s.length,3,e.STATIC_DRAW),this._uvBuf=new Oe(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Oe(e,e.ELEMENT_ARRAY_BUFFER,n,n.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,s){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=h.mat4();return()=>(e&&h.inverseMat4(a.camera.projMatrix,t),t)})());const n=this._scene.canvas.gl,i=this._program,a=this._scene,r=n.drawingBufferWidth,l=n.drawingBufferHeight,o=a.camera.project._state,c=o.near,u=o.far;n.viewport(0,0,r,l),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),i.bind(),je[0]=r,je[1]=l,n.uniform2fv(this._uViewport,je),n.uniform1f(this._uCameraNear,c),n.uniform1f(this._uCameraFar,u),n.uniform1f(this._uDepthCutoff,.01),0===s?n.uniform2fv(this._uSampleOffsets,Ue):n.uniform2fv(this._uSampleOffsets,He),n.uniform1fv(this._uSampleWeights,Ge);const p=e.getDepthTexture(),A=t.getTexture();i.bindTexture(this._uDepthTexture,p,0),i.bindTexture(this._uOcclusionTexture,A,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),n.drawElements(n.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function ke(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Qe(e,t){const s=[];for(let n=0;n<=e;n++)s.push(t[0]*n),s.push(t[1]*n);return s}class We{constructor(e,t,s){s=s||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,s=null){const n=this.gl,i=n.createTexture();return n.bindTexture(n.TEXTURE_2D,i),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),s?n.texStorage2D(n.TEXTURE_2D,1,s,e,t):n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null),i}_touch(...e){let t,s;const n=this.gl;if(this.size?(t=this.size[0],s=this.size[1]):(t=n.drawingBufferWidth,s=n.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===s)return;this.buffer.textures.forEach((e=>n.deleteTexture(e))),n.deleteFramebuffer(this.buffer.framebuf),n.deleteRenderbuffer(this.buffer.renderbuf)}const i=[];let a;e.length>0?i.push(...e.map((e=>this.createTexture(t,s,e)))):i.push(this.createTexture(t,s)),this._hasDepthTexture&&(a=n.createTexture(),n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.DEPTH_COMPONENT32F,t,s,0,n.DEPTH_COMPONENT,n.FLOAT,null));const r=n.createRenderbuffer();n.bindRenderbuffer(n.RENDERBUFFER,r),n.renderbufferStorage(n.RENDERBUFFER,n.DEPTH_COMPONENT32F,t,s);const l=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,l);for(let e=0;e<i.length;e++)n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+e,n.TEXTURE_2D,i[e],0);if(e.length>0&&n.drawBuffers(i.map(((e,t)=>n.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?n.framebufferTexture2D(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.TEXTURE_2D,a,0):n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,r),n.bindTexture(n.TEXTURE_2D,null),n.bindRenderbuffer(n.RENDERBUFFER,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindFramebuffer(n.FRAMEBUFFER,l),!n.isFramebuffer(l))throw"Invalid framebuffer";n.bindFramebuffer(n.FRAMEBUFFER,null);const o=n.checkFramebufferStatus(n.FRAMEBUFFER);switch(o){case n.FRAMEBUFFER_COMPLETE:break;case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+o}this.buffer={framebuf:l,renderbuf:r,texture:i[0],textures:i,depthTexture:a,width:t,height:s},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,s=null,n=null,i=Uint8Array,a=4,r=0){const l=e,o=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,c=new i(a),u=this.gl;return u.readBuffer(u.COLOR_ATTACHMENT0+r),u.readPixels(l,o,1,1,s||u.RGBA,n||u.UNSIGNED_BYTE,c,0),c}readArray(e=null,t=null,s=Uint8Array,n=4,i=0){const a=new s(this.buffer.width*this.buffer.height*n),r=this.gl;return r.readBuffer(r.COLOR_ATTACHMENT0+i),r.readPixels(0,0,this.buffer.width,this.buffer.height,e||r.RGBA,t||r.UNSIGNED_BYTE,a,0),a}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),s=t.pixelData,n=t.canvas,i=t.imageData,a=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,s);const r=this.buffer.width,l=this.buffer.height,o=l/2|0,c=4*r,u=new Uint8Array(4*r);for(let e=0;e<o;++e){const t=e*c,n=(l-e-1)*c;u.set(s.subarray(t,t+c)),s.copyWithin(t,n,n+c),s.set(u,n)}return i.data.set(s),a.putImageData(i,0,0),n}readImage(e){const t=this.gl,s=this._getImageDataCache(),n=s.pixelData,i=s.canvas,a=s.imageData,r=s.context,{width:l,height:o}=this.buffer;t.readPixels(0,0,l,o,t.RGBA,t.UNSIGNED_BYTE,n),a.data.set(n),r.putImageData(a,0,0),r.save(),r.globalCompositeOperation="copy",r.scale(1,-1),r.drawImage(i,0,-o,l,o),r.restore();let c=e.format||"png";return"jpeg"!==c&&"png"!==c&&"bmp"!==c&&(console.error("Unsupported image format: '"+c+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),c="png"),i.toDataURL(`image/${c}`)}_getImageDataCache(e=Uint8Array,t=4){const s=this.buffer.width,n=this.buffer.height;let i=this._imageDataCache;if(i&&(i.width===s&&i.height===n||(this._imageDataCache=null,i=null)),!i){const a=document.createElement("canvas"),r=a.getContext("2d");a.width=s,a.height=n,i={pixelData:new e(s*n*t),canvas:a,context:r,imageData:r.createImageData(s,n),width:s,height:n},this._imageDataCache=i}return i.context.resetTransform(),i}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(e=0){const t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(s){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+s]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(s){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+s]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;this.buffer.textures.forEach((t=>e.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class ze{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const s=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let n=s[e];return n||(n=new We(this.scene.canvas.canvas,this.scene.canvas.gl,t),s[e]=n),n}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Ke(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let s;switch(t){case"WEBGL_depth_texture":s=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":s=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":s=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":s=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:s=e.getExtension(t)}return e._cachedExtensions[t]=s,s}const Ye=function(t,s){s=s||{};const n=new we(t),i=t.canvas.canvas,a=t.canvas.gl,r=!!s.transparent,l=s.alphaDepthMask,o=new e({});let c={},u={},p=!0,A=!0,f=!0,I=!0,y=!0,m=!0,v=!0,w=!0;const g=new ze(t);let E=!1;const T=new Fe(t),b=new Ve(t);function D(){p&&(!function(){for(let e in c)if(c.hasOwnProperty(e)){const t=c[e],s=t.drawableMap,n=t.drawableListPreCull;let i=0;for(let e in s)s.hasOwnProperty(e)&&(n[i++]=s[e]);n.length=i}}(),p=!1,A=!0),A&&(!function(){for(let e in c)if(c.hasOwnProperty(e)){const t=c[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),A=!1,f=!0),f&&function(){for(let e in c)if(c.hasOwnProperty(e)){const t=c[e],s=t.drawableListPreCull,n=t.drawableList;let i=0;for(let e=0,t=s.length;e<t;e++){const t=s[e];t.rebuildRenderFlags(),t.renderFlags.culled||(n[i++]=t)}n.length=i}}()}function P(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),n.reset(),n.backfaces=!0,n.frontface=!0,n.shadowViewMatrix=e.getShadowViewMatrix(),n.shadowProjMatrix=e.getShadowProjMatrix(),a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),a.clearColor(0,0,0,1),a.enable(a.DEPTH_TEST),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];!1!==s.visible&&s.castsShadow&&s.drawShadow&&(s.renderFlags.colorOpaque&&s.drawShadow(n))}}t.unbind()}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!Ke(a,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Ke(a,"WEBGL_compressed_texture_etc"),dxtSupported:!!Ke(a,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Ke(a,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Ke(a,"WEBGL_compressed_texture_pvrtc")&&!Ke(a,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){I=e,f=!0},this.setEdgesEnabled=function(e){y=e,f=!0},this.setSAOEnabled=function(e){m=e,f=!0},this.setPBREnabled=function(e){v=e,f=!0},this.setColorTextureEnabled=function(e){w=e,f=!0},this.needStateSort=function(){A=!0},this.shadowsDirty=function(){},this.imageDirty=function(){f=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){T.init(),b.init(),f=!0},this.addDrawable=function(e,t){const s=t.type;if(!s)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let n=c[s];n||(n={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},c[s]=n),n.count++,n.drawableMap[e]=t,u[e]=t,p=!0},this.removeDrawable=function(e){const t=u[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const s=t.type,n=c[s];--n.count<=0?delete c[s]:delete n.drawableMap[e],delete u[e],p=!0},this.getPickID=function(e){return o.addItem(e)},this.putPickID=function(e){o.removeItem(e)},this.clear=function(e){if(a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),r)a.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;a.clearColor(e[0],e[1],e[2],1)}a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT)},this.needsRender=function(){return f||p||A},this.render=function(e){(e=e||{}).force&&(f=!0),D(),f&&(!function(e){const s=t.sao;m&&s.possible&&function(e){const s=t.sao,i=g.getRenderBuffer("saoDepth",{depthTexture:!0});i.bind(),i.clear(),function(e){n.reset(),n.pass=e.pass,a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),a.clearColor(0,0,0,0),a.enable(a.DEPTH_TEST),a.frontFace(a.CCW),a.enable(a.CULL_FACE),a.depthMask(!0),!1!==e.clear&&a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];!0!==s.culled&&!1!==s.visible&&s.drawDepth&&s.saoEnabled&&(s.renderFlags.colorOpaque&&s.drawDepth(n))}}}(e),i.unbind();const r=g.getRenderBuffer("saoOcclusion");if(r.bind(),r.clear(),T.render(i),r.unbind(),s.blur){const e=g.getRenderBuffer("saoOcclusion2");e.bind(),e.clear(),b.render(i,r,0),e.unbind(),r.bind(),r.clear(),b.render(i,e,1),r.unbind()}}(e);(function(){let e=t._lightsState.lights;for(let t=0,s=e.length;t<s;t++){const s=e[t];s.castsShadow&&P(s)}})(),function(e){const s=[],i=[],o=[],u=[],h=[],p=[],A=[],f=[],E=[],T=[],b=[],D=[],P=[],R=[],C=[],_=[],B=t._lightsState.getAmbientColorAndIntensity();if(n.reset(),n.pass=e.pass,n.withSAO=!1,n.pbrEnabled=v&&!!t.pbrEnabled,n.colorTextureEnabled=w&&!!t.colorTextureEnabled,a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),r)a.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?B:t.canvas.backgroundColor;a.clearColor(e[0],e[1],e[2],1)}a.enable(a.DEPTH_TEST),a.frontFace(a.CCW),a.enable(a.CULL_FACE),a.depthMask(!0),a.lineWidth(1),n.lineWidth=1;const O=t.sao.possible;if(m&&O){const e=g.getRenderBuffer("saoOcclusion");n.occlusionTexture=e?e.getTexture():null}else n.occlusionTexture=null;let S,N,x;const L=Date.now();!1!==e.clear&&a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);let M=0,F=0,H=0,U=0,G=0,j=0,V=0,k=0,Q=0,W=0,z=0,K=0,Y=0,X=0,q=0,J=0;for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(S=0,N=t.length;S<N;S++){if(x=t[S],!0===x.culled||!1===x.visible)continue;const e=x.renderFlags;e.colorOpaque&&(m&&O&&x.saoEnabled?s[M++]=x:x.drawColorOpaque(n)),I&&e.colorTransparent&&(o[H++]=x),e.xrayedSilhouetteTransparent&&(A[V++]=x),e.xrayedSilhouetteOpaque&&(h[G++]=x),e.highlightedSilhouetteTransparent&&(b[z++]=x),e.highlightedSilhouetteOpaque&&(E[Q++]=x),e.selectedSilhouetteTransparent&&(C[q++]=x),e.selectedSilhouetteOpaque&&(P[Y++]=x),y&&(e.edgesOpaque&&(i[F++]=x),e.edgesTransparent&&(u[U++]=x)),e.selectedEdgesTransparent&&(_[J++]=x),e.selectedEdgesOpaque&&(R[X++]=x),e.xrayedEdgesTransparent&&(f[k++]=x),e.xrayedEdgesOpaque&&(p[j++]=x),e.highlightedEdgesTransparent&&(D[K++]=x),e.highlightedEdgesOpaque&&(T[W++]=x)}}if(M>0)for(n.withSAO=!0,S=0;S<M;S++)s[S].drawColorOpaque(n);if(F>0)for(S=0;S<F;S++)i[S].drawEdgesColorOpaque(n);if(G>0)for(S=0;S<G;S++)h[S].drawSilhouetteXRayed(n);if(j>0)for(S=0;S<j;S++)p[S].drawEdgesXRayed(n);if(V>0||k>0||H>0||U>0){if(a.enable(a.CULL_FACE),a.enable(a.BLEND),r?(a.blendEquation(a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA)),n.backfaces=!1,l||a.depthMask(!1),(H>0||U>0)&&a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),U>0)for(S=0;S<U;S++)x=u[S],x.drawEdgesColorTransparent(n);if(H>0)for(S=0;S<H;S++)x=o[S],x.drawColorTransparent(n);if(k>0)for(S=0;S<k;S++)f[S].drawEdgesXRayed(n);if(V>0)for(S=0;S<V;S++)A[S].drawSilhouetteXRayed(n);a.disable(a.BLEND),l||a.depthMask(!0)}if(Q>0||W>0){if(n.lastProgramId=null,t.highlightMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),W>0)for(S=0;S<W;S++)T[S].drawEdgesHighlighted(n);if(Q>0)for(S=0;S<Q;S++)E[S].drawSilhouetteHighlighted(n)}if(z>0||K>0||Q>0){if(n.lastProgramId=null,t.selectedMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),a.enable(a.BLEND),r?(a.blendEquation(a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),a.enable(a.CULL_FACE),K>0)for(S=0;S<K;S++)D[S].drawEdgesHighlighted(n);if(z>0)for(S=0;S<z;S++)b[S].drawSilhouetteHighlighted(n);a.disable(a.BLEND)}if(Y>0||X>0){if(n.lastProgramId=null,t.selectedMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),X>0)for(S=0;S<X;S++)R[S].drawEdgesSelected(n);if(Y>0)for(S=0;S<Y;S++)P[S].drawSilhouetteSelected(n)}if(q>0||J>0){if(n.lastProgramId=null,t.selectedMaterial.glowThrough&&a.clear(a.DEPTH_BUFFER_BIT),a.enable(a.CULL_FACE),a.enable(a.BLEND),r?(a.blendEquation(a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):a.blendFunc(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA),J>0)for(S=0;S<J;S++)_[S].drawEdgesSelected(n);if(q>0)for(S=0;S<q;S++)C[S].drawSilhouetteSelected(n);a.disable(a.BLEND)}const Z=Date.now(),$=d.frame;$.renderTime=(Z-L)/1e3,$.drawElements=n.drawElements,$.drawArrays=n.drawArrays,$.useProgram=n.useProgram,$.bindTexture=n.bindTexture,$.bindArray=n.bindArray;const ee=ge.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<ee;e++)a.activeTexture(a.TEXTURE0+e);a.bindTexture(a.TEXTURE_CUBE_MAP,null),a.bindTexture(a.TEXTURE_2D,null);const te=ge.MAX_VERTEX_ATTRIBS;for(let e=0;e<te;e++)a.disableVertexAttribArray(e)}(e)}(e),d.frame.frameCount++,f=!1)},this.pick=function(){const e=h.vec3();h.mat4();const s=h.mat4(),r=h.vec3(),l=h.vec3([0,1,0]),u=new Te,p=h.vec2(),A=h.vec3(),d=h.vec3(),f=h.vec3();return h.vec3(),h.vec3(),function(I,y=u){let m;y.reset(),D();let v=null,w=null;y.pickSurface=I.pickSurface,I.canvasPos?(A[0]=I.canvasPos[0],A[1]=I.canvasPos[1],v=t.camera.viewMatrix,w=t.camera.projMatrix,y.canvasPos=I.canvasPos):(I.matrix?(v=I.matrix,w=t.camera.projMatrix):(d.set(I.origin||[0,0,0]),f.set(I.direction||[0,0,1]),m=h.addVec3(d,f,e),r[0]=Math.random(),r[1]=Math.random(),r[2]=Math.random(),h.normalizeVec3(r),h.cross3Vec3(f,r,l),v=h.lookAtMat4v(d,m,l,s),w=t.camera.projMatrix,y.origin=d,y.direction=f),A[0]=.5*i.clientWidth,A[1]=.5*i.clientHeight);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];s.setPickMatrices&&s.setPickMatrices(v,w)}}const E=g.getRenderBuffer("pick",{size:[1,1]});E.bind();const T=function(e,s,i,r,l,u){const h=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=u.origin,n.pickViewMatrix=i,n.pickProjMatrix=r,n.pickInvisible=!!l.pickInvisible,n.pickClipPos=[_(s[0]*h,a.drawingBufferWidth),B(s[1]*h,a.drawingBufferHeight)],a.viewport(0,0,1,1),a.depthMask(!0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);const p=l.includeEntityIds,A=l.excludeEntityIds;for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];!s.drawPickMesh||!0!==l.pickInvisible&&!1===s.visible||!1===s.pickable||(p&&!p[s.id]||A&&A[s.id]||s.drawPickMesh(n))}}const d=e.read(0,0),f=d[0]+(d[1]<<8)+(d[2]<<16)+(d[3]<<24);if(f<0)return;return o.items[f]}(E,A,v,w,I,y);if(!T)return E.unbind(),null;const b=T.delegatePickedEntity?T.delegatePickedEntity():T;return b?(I.pickSurface&&(T.canPickTriangle&&T.canPickTriangle()?(!function(e,s,i,r,l,o){if(!s.drawPickTriangles)return;const c=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=o.origin,n.pickViewMatrix=r,n.pickProjMatrix=l,n.pickClipPos=[_(i[0]*c,a.drawingBufferWidth),B(i[1]*c,a.drawingBufferHeight)],a.viewport(0,0,1,1),a.clearColor(0,0,0,0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT),s.drawPickTriangles(n);const u=e.read(0,0);let h=u[0]+256*u[1]+256*u[2]*256+256*u[3]*256*256;h*=3,o.primIndex=h}(E,T,A,v,w,y),T.pickTriangleSurface(v,w,y),y.pickSurfacePrecision=!1):T.canPickWorldPos&&T.canPickWorldPos()&&(p[0]=t.camera.project.near,p[1]=t.camera.project.far,R(E,T,A,v,w,p,y),!1!==I.pickSurfaceNormal&&function(e,s,i,r,l,o){const c=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=o.origin,n.pickViewMatrix=r,n.pickProjMatrix=l,n.pickClipPos=[_(i[0]*c,a.drawingBufferWidth),B(i[1]*c,a.drawingBufferHeight)];const u=g.getRenderBuffer("pick-normal",{size:[3,3]});u.bind(a.RGBA32I),a.viewport(0,0,u.size[0],u.size[1]),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.DEPTH_BUFFER_BIT),a.clearBufferiv(a.COLOR,0,new Int32Array([0,0,0,0])),s.drawPickNormals(n);const p=u.read(1,1,a.RGBA_INTEGER,a.INT,Int32Array,4);u.unbind();const A=[p[0]/h.MAX_INT,p[1]/h.MAX_INT,p[2]/h.MAX_INT];h.normalizeVec3(A),o.worldNormal=A}(0,T,A,v,w,y),y.pickSurfacePrecision=!1)),E.unbind(),y.entity=b,y):(E.unbind(),null)}}();const R=function(){const e=h.vec4(),s=h.vec4(),r=h.vec4(),l=h.vec4(),o=h.vec4(),c=h.mat4(),u=h.mat4(),p=h.mat4();return function(A,d,f,I,y,m,v){const w=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickOrigin=v.origin,n.pickViewMatrix=I,n.pickProjMatrix=y,n.pickZNear=m[0],n.pickZFar=m[1],n.pickElementsCount=d.pickElementsCount,n.pickElementsOffset=d.pickElementsOffset,n.pickClipPos=[_(f[0]*w,a.drawingBufferWidth),B(f[1]*w,a.drawingBufferHeight)],a.viewport(0,0,1,1),a.clearColor(0,0,0,0),a.depthMask(!0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT),d.drawPickDepths(n);const g=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],s=[1/16777216,1/65536,1/256,1];return h.dotVec4(t,s)}(A.read(0,0)),E=(f[0]-i.clientWidth/2)/(i.clientWidth/2),T=-(f[1]-i.clientHeight/2)/(i.clientHeight/2),b=d.origin;let D;if(b){const e=G(I,b,c);D=h.mulMat4(y,e,u)}else D=h.mulMat4(y,I,u);const P=h.inverseMat4(D,p);e[0]=E,e[1]=T,e[2]=-1,e[3]=1;let R=h.transformVec4(P,e);R=h.mulVec4Scalar(R,1/R[3]),s[0]=E,s[1]=T,s[2]=1,s[3]=1;let C=h.transformVec4(P,s);C=h.mulVec4Scalar(C,1/C[3]);const O=h.subVec3(C,R,r),S=h.addVec3(R,h.mulVec4Scalar(O,g,l),o);b&&h.addVec3(S,b),v.worldPos=S}}();function C(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(let t in c){const s=c[t].drawableList;for(let t=0,n=s.length;t<n;t++){const n=s[t];n.drawSnapDepths&&!n.culled&&n.visible&&n.pickable&&n.drawSnapDepths(e)}}return e.snapPickLayerParams}function _(e,t){return e/t*2-1}function B(e,t){return 1-e/t*2}this.snapPick=function(){const e=new Te;return function(s,i,r,l,u=e){if(!r&&!l)return this.pick({canvasPos:s,pickSurface:!0});const p=t.canvas.resolutionScale;n.reset(),n.backfaces=!0,n.frontface=!0,n.pickZNear=t.camera.project.near,n.pickZFar=t.camera.project.far,i=i||30;const A=g.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*i+1,2*i+1]});n.snapVectorA=[_(s[0]*p,a.drawingBufferWidth),B(s[1]*p,a.drawingBufferHeight)],n.snapInvVectorAB=[a.drawingBufferWidth/(2*i),a.drawingBufferHeight/(2*i)],A.bind(a.RGBA32I,a.RGBA32I,a.RGBA8UI),a.viewport(0,0,A.size[0],A.size[1]),a.enable(a.DEPTH_TEST),a.frontFace(a.CCW),a.disable(a.CULL_FACE),a.depthMask(!0),a.disable(a.BLEND),a.depthFunc(a.LEQUAL),a.clear(a.DEPTH_BUFFER_BIT),a.clearBufferiv(a.COLOR,0,new Int32Array([0,0,0,0])),a.clearBufferiv(a.COLOR,1,new Int32Array([0,0,0,0])),a.clearBufferuiv(a.COLOR,2,new Uint32Array([0,0,0,0]));const d=t.camera.viewMatrix,f=t.camera.projMatrix;for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];s.setPickMatrices&&s.setPickMatrices(d,f)}}a.drawBuffers([a.COLOR_ATTACHMENT0,a.COLOR_ATTACHMENT1,a.COLOR_ATTACHMENT2]);const I=function(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(let t in c){const s=c[t].drawableList;for(let t=0,n=s.length;t<n;t++){const n=s[t];n.drawSnapInitDepthBuf&&!n.culled&&n.visible&&n.pickable&&n.drawSnapInitDepthBuf(e)}}return e.snapPickLayerParams}(n),y=[];n.snapPickLayerParams=y,a.depthMask(!1),a.drawBuffers([a.COLOR_ATTACHMENT0]),r&&l?(n.snapMode="edge",C(n),n.snapMode="vertex",n.snapPickLayerNumber++,C(n)):(n.snapMode=r?"vertex":"edge",C(n)),a.depthMask(!0);const m=A.readArray(a.RGBA_INTEGER,a.INT,Int32Array,4),v=A.readArray(a.RGBA_INTEGER,a.INT,Int32Array,4,1),w=A.readArray(a.RGBA_INTEGER,a.UNSIGNED_INT,Uint32Array,4,2);A.unbind();let E=null;const T=4*i+i*A.size[0]*4,b=m.slice(T,T+4),D=v.slice(T,T+4),P=w.slice(T,T+4);if(0!==b[3]){const e=I[Math.abs(b[3])%I.length],t=e.origin,s=e.coordinateScale;E=[b[0]*s[0]+t[0],b[1]*s[1]+t[1],b[2]*s[2]+t[2]],h.normalizeVec3([D[0]/h.MAX_INT,D[1]/h.MAX_INT,D[2]/h.MAX_INT]);const n=P[0]+(P[1]<<8)+(P[2]<<16)+(P[3]<<24);o.items[n]}let R=[];for(let e=0;e<m.length;e+=4)if(m[e+3]>0){const t=Math.floor(e/4),s=A.size[0],n=t%s-Math.floor(s/2),i=Math.floor(t/s)-Math.floor(s/2),a=Math.sqrt(Math.pow(n,2)+Math.pow(i,2));R.push({x:n,y:i,dist:a,isVertex:r&&l?m[e+3]>y.length/2:r,result:[m[e+0],m[e+1],m[e+2],m[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[w[e+0],w[e+1],w[e+2],w[e+3]]})}let O=null,S=null,N=null,x=null;if(R.length>0){R.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),x=R[0].isVertex?"vertex":"edge";const e=R[0].result,t=R[0].normal,s=R[0].id,n=y[e[3]],i=n.origin,a=n.coordinateScale;S=h.normalizeVec3([t[0]/h.MAX_INT,t[1]/h.MAX_INT,t[2]/h.MAX_INT]),O=[e[0]*a[0]+i[0],e[1]*a[1]+i[1],e[2]*a[2]+i[2]],N=o.items[s[0]+(s[1]<<8)+(s[2]<<16)+(s[3]<<24)]}if(null===E&&null==O)return null;let L=null;null!==O&&(L=t.camera.projectWorldPos(O));const M=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return u.reset(),u.snappedToEdge="edge"===x,u.snappedToVertex="vertex"===x,u.worldPos=O,u.worldNormal=S,u.entity=M,u.canvasPos=s,u.snappedCanvasPos=L||s,u}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Le(t,g),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){D(),this._occlusionTester.bindRenderBuf(),n.reset(),n.backfaces=!0,n.frontface=!0,a.viewport(0,0,a.drawingBufferWidth,a.drawingBufferHeight),a.clearColor(0,0,0,0),a.enable(a.DEPTH_TEST),a.disable(a.CULL_FACE),a.disable(a.BLEND),a.clear(a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT);for(let e in c)if(c.hasOwnProperty(e)){const t=c[e].drawableList;for(let e=0,s=t.length;e<s;e++){const s=t[e];s.drawOcclusion&&!0!==s.culled&&!1!==s.visible&&!1!==s.pickable&&s.drawOcclusion(n)}}this._occlusionTester.drawMarkers(n),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,s,n){const i=g.getRenderBuffer("snapshot");let a,r,l,o;for(i.bind(),i.clear(),this.render({force:!0,opaqueOnly:n}),r=0;r<s;r++)l=2*r,o=4*r,a=i.read(e[l],e[l+1]),t[o]=a[0],t[o+1]=a[1],t[o+2]=a[2],t[o+3]=a[3];i.unbind(),f=!0},this.beginSnapshot=function(e={}){const t=g.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),E=!0},this.renderSnapshot=function(){if(!E)return;g.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),f=!0},this.readSnapshot=function(e){return g.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return g.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){if(!E)return;g.getRenderBuffer("snapshot").unbind(),E=!1},this.destroy=function(){c={},u={},g.destroy(),T.destroy(),b.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class Xe extends _{constructor(e,t={}){super(e,t),this.KEY_BACKSPACE=8,this.KEY_TAB=9,this.KEY_ENTER=13,this.KEY_SHIFT=16,this.KEY_CTRL=17,this.KEY_ALT=18,this.KEY_PAUSE_BREAK=19,this.KEY_CAPS_LOCK=20,this.KEY_ESCAPE=27,this.KEY_PAGE_UP=33,this.KEY_PAGE_DOWN=34,this.KEY_END=35,this.KEY_HOME=36,this.KEY_LEFT_ARROW=37,this.KEY_UP_ARROW=38,this.KEY_RIGHT_ARROW=39,this.KEY_DOWN_ARROW=40,this.KEY_INSERT=45,this.KEY_DELETE=46,this.KEY_NUM_0=48,this.KEY_NUM_1=49,this.KEY_NUM_2=50,this.KEY_NUM_3=51,this.KEY_NUM_4=52,this.KEY_NUM_5=53,this.KEY_NUM_6=54,this.KEY_NUM_7=55,this.KEY_NUM_8=56,this.KEY_NUM_9=57,this.KEY_A=65,this.KEY_B=66,this.KEY_C=67,this.KEY_D=68,this.KEY_E=69,this.KEY_F=70,this.KEY_G=71,this.KEY_H=72,this.KEY_I=73,this.KEY_J=74,this.KEY_K=75,this.KEY_L=76,this.KEY_M=77,this.KEY_N=78,this.KEY_O=79,this.KEY_P=80,this.KEY_Q=81,this.KEY_R=82,this.KEY_S=83,this.KEY_T=84,this.KEY_U=85,this.KEY_V=86,this.KEY_W=87,this.KEY_X=88,this.KEY_Y=89,this.KEY_Z=90,this.KEY_LEFT_WINDOW=91,this.KEY_RIGHT_WINDOW=92,this.KEY_SELECT_KEY=93,this.KEY_NUMPAD_0=96,this.KEY_NUMPAD_1=97,this.KEY_NUMPAD_2=98,this.KEY_NUMPAD_3=99,this.KEY_NUMPAD_4=100,this.KEY_NUMPAD_5=101,this.KEY_NUMPAD_6=102,this.KEY_NUMPAD_7=103,this.KEY_NUMPAD_8=104,this.KEY_NUMPAD_9=105,this.KEY_MULTIPLY=106,this.KEY_ADD=107,this.KEY_SUBTRACT=109,this.KEY_DECIMAL_POINT=110,this.KEY_DIVIDE=111,this.KEY_F1=112,this.KEY_F2=113,this.KEY_F3=114,this.KEY_F4=115,this.KEY_F5=116,this.KEY_F6=117,this.KEY_F7=118,this.KEY_F8=119,this.KEY_F9=120,this.KEY_F10=121,this.KEY_F11=122,this.KEY_F12=123,this.KEY_NUM_LOCK=144,this.KEY_SCROLL_LOCK=145,this.KEY_SEMI_COLON=186,this.KEY_EQUAL_SIGN=187,this.KEY_COMMA=188,this.KEY_DASH=189,this.KEY_PERIOD=190,this.KEY_FORWARD_SLASH=191,this.KEY_GRAVE_ACCENT=192,this.KEY_OPEN_BRACKET=219,this.KEY_BACK_SLASH=220,this.KEY_CLOSE_BRACKET=221,this.KEY_SINGLE_QUOTE=222,this.KEY_SPACE=32,this.element=t.element,this.altDown=!1,this.ctrlDown=!1,this.mouseDownLeft=!1,this.mouseDownMiddle=!1,this.mouseDownRight=!1,this.keyDown=[],this.enabled=!0,this.keyboardEnabled=!0,this.mouseover=!1,this.mouseCanvasPos=h.vec2(),this._keyboardEventsElement=t.keyboardEventsElement||document,this._bindEvents()}_bindEvents(){if(this._eventsBound)return;this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,s)=>{if(!this.enabled)return;const n=Math.max(-1,Math.min(1,40*-e.deltaY));t(n)},{passive:!0});{let e,t;const s=2;this.on("mousedown",(s=>{e=s[0],t=s[1]})),this.on("mouseup",(n=>{e>=n[0]-s&&e<=n[0]+s&&t>=n[1]-s&&t<=n[1]+s&&this.fire("mouseclicked",n,!0)}))}this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,s=0,n=0;for(;t.offsetParent;)s+=t.offsetLeft,n+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-s,this.mouseCanvasPos[1]=e.pageY-n}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const qe=new e({});class Je{constructor(e){this.id=qe.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){qe.removeItem(this.id)}}class Ze extends _{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new Je({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],s=e[3];this._state.boundary=[0,0,t,s],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class $e extends _{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],s=this._fovAxis;let n=this._fov;("x"===s||"min"===s&&t<1||"max"===s&&t>1)&&(n/=t),n=Math.min(n,120),h.perspectiveMat4(n*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class et extends _{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,s=e.canvas.boundary,n=s[2],i=s[3],a=n/i;let r,l,o,c;n>i?(r=-t,l=t,o=t/a,c=-t/a):(r=-t*a,l=t*a,o=t,c=-t),h.orthoMat4c(r,l,c,o,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class tt extends _{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){h.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class st extends _{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new Je({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(h.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(h.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,s,n,i){const a=this.scene.canvas.canvas,r=a.offsetWidth/2,l=a.offsetHeight/2;return s[0]=(e[0]-r)/r,s[1]=(e[1]-l)/l,s[2]=t,s[3]=1,h.mulMat4v4(this.inverseMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,n,i),i}destroy(){super.destroy(),this._state.destroy()}}const nt=h.vec3(),it=h.vec3(),at=h.vec3(),rt=h.vec3(),lt=h.vec3(),ot=h.vec3(),ct=h.vec4(),ut=h.vec4(),ht=h.vec4(),pt=h.mat4(),At=h.mat4(),dt=h.vec3(),ft=h.vec3(),It=h.vec3(),yt=h.vec3();class mt extends _{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new Je({deviceMatrix:h.mat4(),hasDeviceMatrix:!1,matrix:h.mat4(),normalMatrix:h.mat4(),inverseMatrix:h.mat4()}),this._perspective=new $e(this),this._ortho=new et(this),this._frustum=new tt(this),this._customProjection=new st(this),this._project=this._perspective,this._eye=h.vec3([0,0,10]),this._look=h.vec3([0,0,0]),this._up=h.vec3([0,1,0]),this._worldUp=h.vec3([0,1,0]),this._worldRight=h.vec3([1,0,0]),this._worldForward=h.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(h.subVec3(this._eye,this._look,dt),h.normalizeVec3(dt,ft),h.mulVec3Scalar(ft,1e3,It),h.addVec3(this._look,It,yt),t=yt):t=this._eye,e.hasDeviceMatrix?(h.lookAtMat4v(t,this._look,this._up,At),h.mulMat4(e.deviceMatrix,At,e.matrix)):h.lookAtMat4v(t,this._look,this._up,e.matrix),h.inverseMat4(this._state.matrix,this._state.inverseMatrix),h.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=h.subVec3(this._eye,this._look,nt);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=h.transformPoint3(pt,t,it),this.eye=h.addVec3(this._look,t,at),this.up=h.transformPoint3(pt,this._up,rt)}orbitPitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._eye,this._look,nt);const s=h.cross3Vec3(h.normalizeVec3(t,it),h.normalizeVec3(this._up,at));h.rotationMat4v(.0174532925*e,s,pt),t=h.transformPoint3(pt,t,rt),this.up=h.transformPoint3(pt,this._up,lt),this.eye=h.addVec3(t,this._look,ot)}yaw(e){let t=h.subVec3(this._look,this._eye,nt);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pt),t=h.transformPoint3(pt,t,it),this.look=h.addVec3(t,this._eye,at),this._gimbalLock&&(this.up=h.transformPoint3(pt,this._up,rt))}pitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._look,this._eye,nt);const s=h.cross3Vec3(h.normalizeVec3(t,it),h.normalizeVec3(this._up,at));h.rotationMat4v(.0174532925*e,s,pt),this.up=h.transformPoint3(pt,this._up,ot),t=h.transformPoint3(pt,t,rt),this.look=h.addVec3(t,this._eye,lt)}pan(e){const t=h.subVec3(this._eye,this._look,nt),s=[0,0,0];let n;if(0!==e[0]){const i=h.cross3Vec3(h.normalizeVec3(t,[]),h.normalizeVec3(this._up,it));n=h.mulVec3Scalar(i,e[0]),s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]}0!==e[1]&&(n=h.mulVec3Scalar(h.normalizeVec3(this._up,at),e[1]),s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]),0!==e[2]&&(n=h.mulVec3Scalar(h.normalizeVec3(t,rt),e[2]),s[0]+=n[0],s[1]+=n[1],s[2]+=n[2]),this.eye=h.addVec3(this._eye,s,lt),this.look=h.addVec3(this._look,s,ot)}zoom(e){const t=h.subVec3(this._eye,this._look,nt),s=Math.abs(h.lenVec3(t,it)),n=Math.abs(s+e);if(n<.5)return;const i=h.normalizeVec3(t,at);this.eye=h.addVec3(this._look,h.mulVec3Scalar(i,n),rt)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=h.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return h.lenVec3(h.subVec3(this._look,this._eye,nt))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=ct,s=ut,n=ht;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,h.mulMat4v4(this.viewMatrix,t,s),h.mulMat4v4(this.projMatrix,s,n),h.mulVec3Scalar(n,1/n[3]),n[3]=1,n[1]*=-1;const i=this.scene.canvas.canvas,a=i.offsetWidth/2,r=i.offsetHeight/2;return[n[0]*a+a,n[1]*r+r]}destroy(){super.destroy(),this._state.destroy()}}class vt extends _{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class wt extends vt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,n=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=n.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new Je({type:"dir",dir:h.vec3([1,1,1]),color:h.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=h.identityMat4());const e=this.scene.camera,t=this._state.dir,s=e.look,n=[s[0]-t[0],s[1]-t[1],s[2]-t[2]],i=[0,1,0];h.lookAtMat4v(n,s,i,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=h.identityMat4()),h.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new We(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class gt extends vt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:h.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Et extends _{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var Tt=function(){const e=[],t=[],s=[],n=[],i=[];let a=0;const r=new Uint16Array(3),l=new Uint16Array(3),o=new Uint16Array(3),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3();return function(y,m,v,w){!function(i,a){const r={};let l,o,c,u;const h=Math.pow(10,4);let p,A,d=0;for(p=0,A=i.length;p<A;p+=3)l=i[p],o=i[p+1],c=i[p+2],u=Math.round(l*h)+"_"+Math.round(o*h)+"_"+Math.round(c*h),void 0===r[u]&&(r[u]=d/3,e[d++]=l,e[d++]=o,e[d++]=c),t[p/3]=r[u];for(p=0,A=a.length;p<A;p++)n[p]=t[a[p]],s[n[p]]=a[p]}(y,m),function(t,s){a=0;for(let y=0,m=t;y<m;y+=3){const t=3*n[y],m=3*n[y+1],v=3*n[y+2];s?(r[0]=e[t],r[1]=e[t+1],r[2]=e[t+2],l[0]=e[m],l[1]=e[m+1],l[2]=e[m+2],o[0]=e[v],o[1]=e[v+1],o[2]=e[v+2],h.decompressPosition(r,s,c),h.decompressPosition(l,s,u),h.decompressPosition(o,s,p)):(c[0]=e[t],c[1]=e[t+1],c[2]=e[t+2],u[0]=e[m],u[1]=e[m+1],u[2]=e[m+2],p[0]=e[v],p[1]=e[v+1],p[2]=e[v+2]),h.subVec3(p,u,A),h.subVec3(c,u,d),h.cross3Vec3(A,d,f),h.normalizeVec3(f,I);const w=i[a]||(i[a]={normal:h.vec3()});w.normal[0]=I[0],w.normal[1]=I[1],w.normal[2]=I[2],a++}}(m.length,v);const g=[],E=Math.cos(h.DEGTORAD*w),T={};let b,D,P,R,C,_,B,O,S,N,x,L=!1;for(let e=0,t=m.length;e<t;e+=3){const t=e/3;for(let s=0;s<3;s++)b=n[e+s],D=n[e+(s+1)%3],P=Math.min(b,D),R=Math.max(b,D),C=P+","+R,void 0===T[C]?T[C]={index1:P,index2:R,face1:t,face2:void 0}:T[C].face2=t}for(C in T)_=T[C],void 0!==_.face2&&(B=i[_.face1].normal,O=i[_.face2].normal,S=h.dotVec3(B,O),S>E)||(N=s[_.index1],x=s[_.index2],(!L&&N>65535||x>65535)&&(L=!0),g.push(N),g.push(x));return L?new Uint32Array(g):new Uint16Array(g)}}();const bt=function(){const e=h.mat4(),t=h.mat4();return function(s,n){n=n||h.mat4();const i=s[0],a=s[1],r=s[2],l=s[3]-i,o=s[4]-a,c=s[5]-r,u=65535;return h.identityMat4(e),h.translationMat4v(s,e),h.identityMat4(t),h.scalingMat4v([l/u,o/u,c/u],t),h.mulMat4(e,t,n),n}}();var Dt=function(){const e=h.mat4(),t=h.mat4();return function(s,n,i){const a=new Uint16Array(s.length),r=new Float32Array([i[0]!==n[0]?65535/(i[0]-n[0]):0,i[1]!==n[1]?65535/(i[1]-n[1]):0,i[2]!==n[2]?65535/(i[2]-n[2]):0]);let l;for(l=0;l<s.length;l+=3)a[l+0]=Math.max(0,Math.min(65535,Math.floor((s[l+0]-n[0])*r[0]))),a[l+1]=Math.max(0,Math.min(65535,Math.floor((s[l+1]-n[1])*r[1]))),a[l+2]=Math.max(0,Math.min(65535,Math.floor((s[l+2]-n[2])*r[2])));h.identityMat4(e),h.translationMat4v(n,e),h.identityMat4(t),h.scalingMat4v([(i[0]-n[0])/65535,(i[1]-n[1])/65535,(i[2]-n[2])/65535],t);return{quantized:a,decodeMatrix:h.mulMat4(e,t,h.identityMat4())}}}();var Pt=function(){const e=h.mat3(),t=h.mat3();return function(s,n,i){const a=new Uint16Array(s.length),r=new Float32Array([65535/(i[0]-n[0]),65535/(i[1]-n[1])]);let l;for(l=0;l<s.length;l+=2)a[l+0]=Math.max(0,Math.min(65535,Math.floor((s[l+0]-n[0])*r[0]))),a[l+1]=Math.max(0,Math.min(65535,Math.floor((s[l+1]-n[1])*r[1])));h.identityMat3(e),h.translationMat3v(n,e),h.identityMat3(t),h.scalingMat3v([(i[0]-n[0])/65535,(i[1]-n[1])/65535],t);return{quantized:a,decodeMatrix:h.mulMat3(e,t,h.identityMat3())}}}();function Rt(e,t,s,n){let i=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),a=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(a))*(i>=0?1:-1),t=(1-Math.abs(i))*(a>=0?1:-1);i=e,a=t}return new Int8Array([Math[s](127.5*i+(i<0?-1:0)),Math[n](127.5*a+(a<0?-1:0))])}function Ct(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}function _t(e,t,s){return e[t]*s[0]+e[t+1]*s[1]+e[t+2]*s[2]}const Bt={getPositionsBounds:function(e){const t=new Float32Array(3),s=new Float32Array(3);let n,i;for(n=0;n<3;n++)t[n]=Number.MAX_VALUE,s[n]=-Number.MAX_VALUE;for(n=0;n<e.length;n+=3)for(i=0;i<3;i++)t[i]=Math.min(t[i],e[n+i]),s[i]=Math.max(s[i],e[n+i]);return{min:t,max:s}},createPositionsDecodeMatrix:bt,compressPositions:Dt,compressPosition:function(e,t,s){const n=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);s[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*n[0]))),s[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*n[1]))),s[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*n[2])))},decompressPositions:function(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[12],s[n+1]=e[n+1]*t[5]+t[13],s[n+2]=e[n+2]*t[10]+t[14];return s},decompressPosition:function(e,t,s){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s},decompressAABB:function(e,t,s=e){return s[0]=e[0]*t[0]+t[12],s[1]=e[1]*t[5]+t[13],s[2]=e[2]*t[10]+t[14],s[3]=e[3]*t[0]+t[12],s[4]=e[4]*t[5]+t[13],s[5]=e[5]*t[10]+t[14],s},getUVBounds:function(e){const t=new Float32Array(2),s=new Float32Array(2);let n,i;for(n=0;n<2;n++)t[n]=Number.MAX_VALUE,s[n]=-Number.MAX_VALUE;for(n=0;n<e.length;n+=2)for(i=0;i<2;i++)t[i]=Math.min(t[i],e[n+i]),s[i]=Math.max(s[i],e[n+i]);return{min:t,max:s}},compressUVs:Pt,decompressUVs:function(e,t,s=new Float32Array(e.length)){for(let n=0,i=e.length;n<i;n+=3)s[n+0]=e[n+0]*t[0]+t[6],s[n+1]=e[n+1]*t[4]+t[7];return s},decompressUV:function(e,t,s){s[0]=e[0]*t[0]+t[6],s[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let s,n,i,a,r;for(let l=0;l<e.length;l+=3)i=s=Rt(e,l,"floor","floor"),n=Ct(s),a=r=_t(e,l,n),s=Rt(e,l,"ceil","floor"),n=Ct(s),a=_t(e,l,n),a>r&&(i=s,r=a),s=Rt(e,l,"floor","ceil"),n=Ct(s),a=_t(e,l,n),a>r&&(i=s,r=a),s=Rt(e,l,"ceil","ceil"),n=Ct(s),a=_t(e,l,n),a>r&&(i=s,r=a),t[l]=i[0],t[l+1]=i[1];return t},decompressNormals:function(e,t){for(let s=0,n=0,i=e.length;s<i;s+=2){let i=e[s+0],a=e[s+1];i=(2*i+1)/255,a=(2*a+1)/255;const r=1-Math.abs(i)-Math.abs(a);r<0&&(i=(1-Math.abs(a))*(i>=0?1:-1),a=(1-Math.abs(i))*(a>=0?1:-1));const l=Math.sqrt(i*i+a*a+r*r);t[n+0]=i/l,t[n+1]=a/l,t[n+2]=r/l,n+=3}return t},decompressNormal:function(e,t){let s=e[0],n=e[1];s=(2*s+1)/255,n=(2*n+1)/255;const i=1-Math.abs(s)-Math.abs(n);i<0&&(s=(1-Math.abs(n))*(s>=0?1:-1),n=(1-Math.abs(s))*(n>=0?1:-1));const a=Math.sqrt(s*s+n*n+i*i);return t[0]=s/a,t[1]=n/a,t[2]=i/a,t}},Ot=d.memory,St=h.AABB3();class Nt extends Et{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Je({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Bt.getPositionsBounds(t.positions),n=Bt.compressPositions(t.positions,e.min,e.max);s.positions=n.quantized,s.positionsDecodeMatrix=n.decodeMatrix}else s.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(s.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Bt.getUVBounds(t.uv),n=Bt.compressUVs(t.uv,e.min,e.max);s.uv=n.quantized,s.uvDecodeMatrix=n.decodeMatrix}else s.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?s.normals=Bt.compressNormals(t.normals):s.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(s.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Ot.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Ot.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Ot.positions+=e.positionsBuf.numItems),e.normals){let s=e.compressGeometry;e.normalsBuf=new Oe(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,s),Ot.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Ot.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Oe(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Ot.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=Tt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,s,s.length,1,t.STATIC_DRAW),Ot.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,s=h.buildPickTriangles(e.positions,e.indices,e.compressGeometry),n=s.positions,i=s.colors;this._pickTrianglePositionsBuf=new Oe(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,4,t.STATIC_DRAW,!0),Ot.positions+=this._pickTrianglePositionsBuf.numItems,Ot.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Bt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,s=t.positions;if(s)if(s.length===e.length){if(this._state.compressGeometry){const s=Bt.getPositionsBounds(e),n=Bt.compressPositions(e,s.min,s.max);e=n.quantized,t.positionsDecodeMatrix=n.decodeMatrix}s.set(e),t.positionsBuf&&t.positionsBuf.setData(s),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Bt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,s=t.normals;s?s.length===e.length?(s.set(e),t.normalsBuf&&t.normalsBuf.setData(s),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Bt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,s=t.uv;s?s.length===e.length?(s.set(e),t.uvBuf&&t.uvBuf.setData(s),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,s=t.colors;s?s.length===e.length?(s.set(e),t.colorsBuf&&t.colorsBuf.setData(s),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=h.AABB3()),h.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=h.OBB3()),h.positions3ToAABB3(this._state.positions,St,this._state.positionsDecodeMatrix),h.AABB3ToOBB3(St,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Ot.meshes--}}function xt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.ySize||1;s<0&&(console.error("negative ySize not allowed - will invert"),s*=-1);let n=e.zSize||1;n<0&&(console.error("negative zSize not allowed - will invert"),n*=-1);const i=e.center,a=i?i[0]:0,r=i?i[1]:0,l=i?i[2]:0,o=-t+a,c=-s+r,u=-n+l,h=t+a,p=s+r,A=n+l;return m.apply(e,{positions:[h,p,A,o,p,A,o,c,A,h,c,A,h,p,A,h,c,A,h,c,u,h,p,u,h,p,A,h,p,u,o,p,u,o,p,A,o,p,A,o,p,u,o,c,u,o,c,A,o,c,u,h,c,u,h,c,A,o,c,A,h,c,u,o,c,u,o,p,u,h,p,u],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Lt extends _{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const Mt={opaque:0,mask:1,blend:2},Ft=["opaque","mask","blend"];class Ht extends Lt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"PhongMaterial",ambient:h.vec3([1,1,1]),diffuse:h.vec3([1,1,1]),specular:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Mt[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Ft[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Ut={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Gt extends Lt{get type(){return"EmphasisMaterial"}get presets(){return Ut}constructor(e,t={}){super(e,t),this._state=new Je({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Ut[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ut).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const jt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Vt extends Lt{get type(){return"EdgeMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new Je({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=jt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(jt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const kt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Qt extends _{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=h.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return kt}set units(e){e||(e="meters");kt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=h.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=h.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class Wt extends _{constructor(e,t={}){super(e,t),this._supported=ge.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const zt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Kt extends Lt{get type(){return"PointsMaterial"}get presets(){return zt}constructor(e,t={}){super(e,t),this._state=new Je({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=zt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(zt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const Yt={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Xt extends Lt{get type(){return"LinesMaterial"}get presets(){return Yt}constructor(e,t={}){super(e,t),this._state=new Je({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=Yt[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Yt).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function qt(e,t){const s={};let n,i;for(let a=0,r=t.length;a<r;a++)n=t[a],i=e.components[n],i?i.isEntity?s[n]=!0:e.warn("pick(): Component is not an Entity: "+n):e.warn("pick(): Component not found: "+n);return s}class Jt extends _{get type(){return"Scene"}constructor(e,t={}){super(null,t);const s=t.canvasElement||document.getElementById(t.canvasId);if(!(s instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";this._tickifiedFunctions={};const n=!!t.transparent,i=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new ve(this,{dontClear:!0,canvas:s,spinnerElementId:t.spinnerElementId,transparent:n,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new Ye(this,{transparent:n,alphaDepthMask:i}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const s=[];for(let e=0,n=t.length;e<n;e++)s.push("cp");return s.push(";"),e=s.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let s=0,n=this.sectionPlanes.length;s<n;s++)if(this.sectionPlanes[s].id===t.id)return this.sectionPlanes.splice(s,1),void(e=null)}},this._lightsState=new function(){const e=h.vec4([0,0,0,0]),t=h.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let s=null,n=null;this.getHash=function(){if(s)return s;const e=[],t=this.lights;let n;for(let s=0,i=t.length;s<i;s++)n=t[s],e.push("/"),e.push(n.type),e.push("world"===n.space?"w":"v"),n.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),s=e.join(""),s},this.addLight=function(e){this.lights.push(e),n=null,s=null},this.removeLight=function(e){for(let t=0,i=this.lights.length;t<i;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),n&&n.id===e.id&&(n=null),void(s=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),s=null},this.removeReflectionMap=function(e){for(let t=0,n=this.reflectionMaps.length;t<n;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(s=null)},this.addLightMap=function(e){this.lightMaps.push(e),s=null},this.removeLightMap=function(e){for(let t=0,n=this.lightMaps.length;t<n;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(s=null)},this.getAmbientColorAndIntensity=function(){if(!n)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){n=t;break}}if(n){const e=n.color,s=n.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=s,t}return e}},this.input=new Xe(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new Qt(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Wt(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,R._addScene(this),this._initDefaults(),this._viewport=new Ze(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new mt(this,{id:"default.camera",dontClear:!0}),new gt(this,{color:[1,1,1],intensity:.7}),new wt(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new wt(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+m.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=h.createUUID();this.components[e.id]=e;const t=e.type;let s=this.types[e.type];s||(s=this.types[t]={}),s[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,s=e.type;delete this.components[t];const n=this.types[s];n&&(delete n[t],m.isEmptyObject(n)&&delete this.types[s]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_objectHighlightedUpdated(e,t=!0){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null,t&&this.fire("objectHighlighted",e,!0)}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const s=this.components[t];s._webglContextRestored&&s._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&R.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const s=this._passes,n=this._clearEachPass;let i,a;for(i=0;i<s;i++)t.pass=i,this.fire("rendering",t,!0),a=n||0===i,this._renderer.render({pass:i,clear:a,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=h.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!m.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||xt(Nt)}get material(){return this.components["default.material"]||new Ht(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new Gt(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new Gt(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new Gt(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new Vt(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Kt(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new Xt(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=h.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=h.AABB3());let e,t=h.MAX_DOUBLE,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MIN_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE;const l=this._collidables;let o,c=!1;for(const u in l)if(l.hasOwnProperty(u)){if(o=l[u],!1===o.collidable)continue;e=o.aabb,e[0]<t&&(t=e[0]),e[1]<s&&(s=e[1]),e[2]<n&&(n=e[2]),e[3]>i&&(i=e[3]),e[4]>a&&(a=e[4]),e[5]>r&&(r=e[5]),c=!0}c||(t=-100,s=-100,n=-100,i=100,a=100,r=100),this._aabb[0]=t,this._aabb[1]=s,this._aabb[2]=n,this._aabb[3]=i,this._aabb[4]=a,this._aabb[5]=r,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const s=e.includeEntities||e.include;s&&(e.includeEntityIds=qt(this,s));const n=e.excludeEntities||e.exclude;return n&&(e.excludeEntityIds=qt(this,n)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,s=e.length;t<s;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,s=e.length;t<s;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,s=e.length;t<s;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,s=e.length;t<s;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(m.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,s=h.MAX_DOUBLE,n=h.MAX_DOUBLE,i=h.MAX_DOUBLE,a=h.MIN_DOUBLE,r=h.MIN_DOUBLE,l=h.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const o=e.aabb;o[0]<s&&(s=o[0]),o[1]<n&&(n=o[1]),o[2]<i&&(i=o[2]),o[3]>a&&(a=o[3]),o[4]>r&&(r=o[4]),o[5]>l&&(l=o[5]),t=!0}})),t){const e=h.AABB3();return e[0]=s,e[1]=n,e[2]=i,e[3]=a,e[4]=r,e[5]=l,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const s=e.visible!==t;return e.visible=t,s}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const s=e.collidable!==t;return e.collidable=t,s}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const s=e.culled!==t;return e.culled=t,s}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const s=e.selected!==t;return e.selected=t,s}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const s=e.highlighted!==t;return e.highlighted=t,s}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const s=e.xrayed!==t;return e.xrayed=t,s}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const s=e.edges!==t;return e.edges=t,s}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const s=e.opacity!==t;return e.opacity=t,s}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const s=e.pickable!==t;return e.pickable=t,s}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){m.isString(e)&&(e=[e]);let s=!1;for(let n=0,i=e.length;n<i;n++){const i=e[n];let a=this.objects[i];if(a)s=t(a)||s;else{const e=this.modelIds;for(let n=0,r=e.length;n<r;n++){const r=e[n],l=h.globalizeObjectId(r,i);a=this.objects[l],a&&(s=t(a)||s)}}}return s}tickify(e){const t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;let s,n=0,i=0;const a=function(...e){s=e,i++},r=this.on("tick",(()=>{i>n&&(n=i,e(...s))}));return this._tickifiedFunctions[t]={tickSubId:r,wrapperFunc:a},a}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const Zt=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene._lightsState,i=e._geometry._state,a=e._state.billboard,r=e._state.stationary,l=s.sectionPlanes.length>0,o=!!i.compressGeometry,c=[];c.push("#version 300 es"),c.push("// Lambertian drawing vertex shader"),c.push("in vec3 position;"),c.push("uniform mat4 modelMatrix;"),c.push("uniform mat4 viewMatrix;"),c.push("uniform mat4 projMatrix;"),c.push("uniform vec4 colorize;"),c.push("uniform vec3 offset;"),o&&c.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(c.push("uniform float logDepthBufFC;"),c.push("out float vFragDepth;"),c.push("bool isPerspectiveMatrix(mat4 m) {"),c.push(" return (m[2][3] == - 1.0);"),c.push("}"),c.push("out float isPerspective;"));l&&c.push("out vec4 vWorldPosition;");if(c.push("uniform vec4 lightAmbient;"),c.push("uniform vec4 materialColor;"),c.push("uniform vec3 materialEmissive;"),i.normalsBuf){c.push("in vec3 normal;"),c.push("uniform mat4 modelNormalMatrix;"),c.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(c.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&c.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&c.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(c.push("uniform vec3 lightPos"+e+";"),c.push("uniform vec3 lightDir"+e+";")))}o&&(c.push("vec3 octDecode(vec2 oct) {"),c.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),c.push(" if (v.z < 0.0) {"),c.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),c.push(" }"),c.push(" return normalize(v);"),c.push("}"))}c.push("out vec4 vColor;"),"points"===i.primitiveName&&c.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(c.push("void billboard(inout mat4 mat) {"),c.push(" mat[0][0] = 1.0;"),c.push(" mat[0][1] = 0.0;"),c.push(" mat[0][2] = 0.0;"),"spherical"===a&&(c.push(" mat[1][0] = 0.0;"),c.push(" mat[1][1] = 1.0;"),c.push(" mat[1][2] = 0.0;")),c.push(" mat[2][0] = 0.0;"),c.push(" mat[2][1] = 0.0;"),c.push(" mat[2][2] =1.0;"),c.push("}"));c.push("void main(void) {"),c.push("vec4 localPosition = vec4(position, 1.0); "),c.push("vec4 worldPosition;"),o&&c.push("localPosition = positionsDecodeMatrix * localPosition;");i.normalsBuf&&(o?c.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):c.push("vec4 localNormal = vec4(normal, 0.0); "),c.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),c.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));c.push("mat4 viewMatrix2 = viewMatrix;"),c.push("mat4 modelMatrix2 = modelMatrix;"),r&&c.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===a||"cylindrical"===a?(c.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),c.push("billboard(modelMatrix2);"),c.push("billboard(viewMatrix2);"),c.push("billboard(modelViewMatrix);"),i.normalsBuf&&(c.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),c.push("billboard(modelNormalMatrix2);"),c.push("billboard(viewNormalMatrix2);"),c.push("billboard(modelViewNormalMatrix);")),c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(c.push("worldPosition = modelMatrix2 * localPosition;"),c.push("worldPosition.xyz = worldPosition.xyz + offset;"),c.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i.normalsBuf&&c.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(c.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),c.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),c.push("float lambertian = 1.0;"),i.normalsBuf)for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?c.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):c.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?c.push("viewLightDir = normalize(lightDir"+e+");"):c.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}c.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),c.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}c.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),l&&c.push("vWorldPosition = worldPosition;");"points"===i.primitiveName&&c.push("gl_PointSize = pointSize;");c.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(c.push("vFragDepth = 1.0 + clipPos.w;"),c.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return c.push("gl_Position = clipPos;"),c.push("}"),c}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState;e._material._state;const n=e._geometry._state,i=s.sectionPlanes.length>0,a=t.gammaOutput,r=[];r.push("#version 300 es"),r.push("// Lambertian drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(i){r.push("in vec4 vWorldPosition;"),r.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}r.push("in vec4 vColor;"),a&&(r.push("uniform float gammaFactor;"),r.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}"));if(r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}"points"===n.primitiveName&&(r.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),r.push("float r = dot(cxy, cxy);"),r.push("if (r > 1.0) {"),r.push(" discard;"),r.push("}"));t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");a?r.push("outColor = linearToGamma(vColor, gammaFactor);"):r.push("outColor = vColor;");return r.push("}"),r}(e)):(this.vertex=function(e){const t=e.scene;e._material;const s=e._state,n=t._sectionPlanesState,i=e._geometry._state,a=t._lightsState;let r;const l=s.billboard,o=s.background,c=s.stationary,u=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),h=ts(e),p=n.sectionPlanes.length>0,A=es(e),d=!!i.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),d&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),p&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));a.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(h){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===r.type&&"view"===r.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));d&&(f.push("vec3 octDecode(vec2 oct) {"),f.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push(" if (v.z < 0.0) {"),f.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}u&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),d&&f.push("uniform mat3 uvDecodeMatrix;"));i.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===i.primitiveName&&f.push("uniform float pointSize;");"spherical"!==l&&"cylindrical"!==l||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===l&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("out vec4 vShadowPosFromLight"+e+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),d&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(d?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),c?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):o&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),h&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(h){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)r=a.lights[e],"ambient"!==r.type&&("dir"===r.type&&"world"===r.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===r.type&&("world"===r.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}u&&(d?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));i.colors&&f.push("vColor = color;");"points"===i.primitiveName&&f.push("gl_PointSize = pointSize;");p&&f.push("vWorldPosition = worldPosition;");f.push(" vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));o&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),A){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=e._material,n=e._geometry._state,i=e.scene._sectionPlanesState,a=e.scene._lightsState,r=e._material._state,l=i.sectionPlanes.length>0,o=ts(e),c=n.uvBuf,u="PhongMaterial"===r.type,h="MetallicMaterial"===r.type,p="SpecularMaterial"===r.type,A=es(e);t.gammaInput;const d=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));A&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" 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.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),d&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(l){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var I=0;I<i.sectionPlanes.length;I++)f.push("uniform bool sectionPlaneActive"+I+";"),f.push("uniform vec3 sectionPlanePos"+I+";"),f.push("uniform vec3 sectionPlaneDir"+I+";")}o&&(a.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),a.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),u&&((a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = "+$t[a.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(h||p)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),a.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+$t[a.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(a.lightMaps.length>0||a.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),a.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),n.colors&&f.push("in vec4 vColor;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._occlusionMap||s._alphaMap)&&f.push("in vec2 vUV;");o&&(a.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));r.ambient&&f.push("uniform vec3 materialAmbient;");r.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==r.alpha&&null!==r.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");r.emissive&&f.push("uniform vec3 materialEmissive;");r.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==r.glossiness&&null!==r.glossiness&&f.push("uniform float materialGlossiness;");void 0!==r.shininess&&null!==r.shininess&&f.push("uniform float materialShininess;");r.specular&&f.push("uniform vec3 materialSpecular;");void 0!==r.metallic&&null!==r.metallic&&f.push("uniform float materialMetallic;");void 0!==r.roughness&&null!==r.roughness&&f.push("uniform float materialRoughness;");void 0!==r.specularF0&&null!==r.specularF0&&f.push("uniform float materialSpecularF0;");c&&s._ambientMap&&(f.push("uniform sampler2D ambientMap;"),s._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));c&&s._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),s._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));c&&s._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),s._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));c&&s._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),s._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));o&&c&&s._metallicMap&&(f.push("uniform sampler2D metallicMap;"),s._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));o&&c&&s._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),s._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));o&&c&&s._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),s._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));o&&s._normalMap&&(f.push("uniform sampler2D normalMap;"),s._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));c&&s._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),s._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));c&&s._alphaMap&&(f.push("uniform sampler2D alphaMap;"),s._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));o&&c&&s._specularMap&&(f.push("uniform sampler2D specularMap;"),s._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));o&&c&&s._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),s._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));o&&c&&s._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),s._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));o&&(s._diffuseFresnel||s._specularFresnel||s._alphaFresnel||s._emissiveFresnel||s._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),s._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),s._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),s._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),s._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),s._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),o)for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("in vec4 vViewLightReverseDirAndDist"+e+";"))}if(A)for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("in vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("out vec4 outColor;"),f.push("void main(void) {"),l){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(I=0;I<i.sectionPlanes.length;I++)f.push("if (sectionPlaneActive"+I+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+I+".xyz, vWorldPosition.xyz - sectionPlanePos"+I+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===n.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),r.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");r.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):r.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");n.colors&&f.push("diffuseColor *= vColor.rgb;");r.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");r.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==r.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");n.colors&&f.push("alpha *= vColor.a;");void 0!==r.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==r.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==r.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==r.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");c&&(o&&s._normalMap||s._ambientMap||s._baseColorMap||s._diffuseMap||s._occlusionMap||s._emissiveMap||s._metallicMap||s._roughnessMap||s._metallicRoughnessMap||s._specularMap||s._glossinessMap||s._specularGlossinessMap||s._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));c&&s._ambientMap&&(s._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+$t[s._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));c&&s._diffuseMap&&(s._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+$t[s._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));c&&s._baseColorMap&&(s._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+$t[s._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));c&&s._emissiveMap&&(s._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+$t[s._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));c&&s._alphaMap&&(s._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));c&&s._occlusionMap&&(s._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(o&&(a.lights.length>0||a.lightMaps.length>0||a.reflectionMaps.length>0)){c&&s._normalMap?(s._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),c&&s._specularMap&&(s._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),c&&s._glossinessMap&&(s._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),c&&s._specularGlossinessMap&&(s._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),c&&s._metallicMap&&(s._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),c&&s._roughnessMap&&(s._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),c&&s._metallicRoughnessMap&&(s._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),s._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),s._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),s._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),s._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),u&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),p&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),h&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),a.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),u&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(p||h)&&(a.lightMaps.length>0||a.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=a.lights.length;e<t;e++){const t=a.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),A&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push(" for (int y = -3; y <= 3; y++) {"),f.push(" float texelDepth = unpackDepth(texture(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push(" if (fragmentDepth.z < texelDepth) {"),f.push(" shadow += 1.0;"),f.push(" }"),f.push(" }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color = lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),u&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(p||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}u?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");f.push("vec4 fragColor = vec4(outgoingLight, alpha) * colorize;"),d&&f.push("fragColor = linearToGamma(fragColor, gammaFactor);");f.push("outColor = fragColor;"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return f.push("}"),f}(e))},$t={};function es(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,s=t.length;e<s;e++)if(t[e].castsShadow)return!0;return!1}function ts(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}$t[3e3]="linearToLinear",$t[3001]="sRGBToLinear";const ss=h.vec3(),ns=new e({}),is=function(e,t){this.id=ns.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Zt(t),this._allocate(t)},as={};is.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let n=as[s];if(!n){if(n=new is(s,e),n.errors)return console.log(n.errors.join("\n")),null;as[s]=n,d.memory.programs++}return n._useCount++,n},is.prototype.put=function(){0==--this._useCount&&(ns.removeItem(this.id),this._program&&this._program.destroy(),delete as[this._hash],d.memory.programs--)},is.prototype.webglContextRestored=function(){this._program=null},is.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=ge.MAX_TEXTURE_UNITS,n=t.scene,i=t._material,a=n.canvas.gl,r=this._program,l=t._state,o=t._material._state,c=t._geometry._state,u=n.camera,h=t.origin,p=l.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,p&&a.depthFunc(a.LEQUAL),this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(l.originHash,h):u.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,u.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,h?k(n.dist,n.dir,h,ss):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(o.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=o.backfaces;e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t);const n=o.frontface;switch(e.frontface!==n&&(n?a.frontFace(a.CCW):a.frontFace(a.CW),e.frontface=n),e.lineWidth!==o.lineWidth&&(a.lineWidth(o.lineWidth),e.lineWidth=o.lineWidth),this._uPointSize&&a.uniform1f(this._uPointSize,o.pointSize),o.type){case"LambertMaterial":this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialColor&&a.uniform4f(this._uMaterialColor,o.color[0],o.color[1],o.color[2],o.alpha),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive);break;case"PhongMaterial":this._uMaterialShininess&&a.uniform1f(this._uMaterialShininess,o.shininess),this._uMaterialAmbient&&a.uniform3fv(this._uMaterialAmbient,o.ambient),this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0),i._ambientMap&&i._ambientMap._state.texture&&this._uMaterialAmbientMap&&(r.bindTexture(this._uMaterialAmbientMap,i._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMaterialAmbientMapMatrix&&a.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,i._ambientMap._state.matrix)),i._diffuseMap&&i._diffuseMap._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,i._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,i._diffuseMap._state.matrix)),i._specularMap&&i._specularMap._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,i._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,i._specularMap._state.matrix)),i._emissiveMap&&i._emissiveMap._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,i._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,i._emissiveMap._state.matrix)),i._alphaMap&&i._alphaMap._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,i._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,i._alphaMap._state.matrix)),i._reflectivityMap&&i._reflectivityMap._state.texture&&this._uReflectivityMap&&(r.bindTexture(this._uReflectivityMap,i._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,this._uReflectivityMapMatrix&&a.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,i._reflectivityMap._state.matrix)),i._normalMap&&i._normalMap._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,i._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,i._normalMap._state.matrix)),i._occlusionMap&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,i._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,i._occlusionMap._state.matrix)),i._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&a.uniform1f(this._uDiffuseFresnelEdgeBias,i._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&a.uniform1f(this._uDiffuseFresnelCenterBias,i._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&a.uniform3fv(this._uDiffuseFresnelEdgeColor,i._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&a.uniform3fv(this._uDiffuseFresnelCenterColor,i._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&a.uniform1f(this._uDiffuseFresnelPower,i._diffuseFresnel.power)),i._specularFresnel&&(this._uSpecularFresnelEdgeBias&&a.uniform1f(this._uSpecularFresnelEdgeBias,i._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&a.uniform1f(this._uSpecularFresnelCenterBias,i._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&a.uniform3fv(this._uSpecularFresnelEdgeColor,i._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&a.uniform3fv(this._uSpecularFresnelCenterColor,i._specularFresnel.centerColor),this._uSpecularFresnelPower&&a.uniform1f(this._uSpecularFresnelPower,i._specularFresnel.power)),i._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&a.uniform1f(this._uAlphaFresnelEdgeBias,i._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&a.uniform1f(this._uAlphaFresnelCenterBias,i._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&a.uniform3fv(this._uAlphaFresnelEdgeColor,i._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&a.uniform3fv(this._uAlphaFresnelCenterColor,i._alphaFresnel.centerColor),this._uAlphaFresnelPower&&a.uniform1f(this._uAlphaFresnelPower,i._alphaFresnel.power)),i._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&a.uniform1f(this._uReflectivityFresnelEdgeBias,i._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&a.uniform1f(this._uReflectivityFresnelCenterBias,i._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&a.uniform3fv(this._uReflectivityFresnelEdgeColor,i._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&a.uniform3fv(this._uReflectivityFresnelCenterColor,i._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&a.uniform1f(this._uReflectivityFresnelPower,i._reflectivityFresnel.power)),i._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&a.uniform1f(this._uEmissiveFresnelEdgeBias,i._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&a.uniform1f(this._uEmissiveFresnelCenterBias,i._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&a.uniform3fv(this._uEmissiveFresnelEdgeColor,i._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&a.uniform3fv(this._uEmissiveFresnelCenterColor,i._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&a.uniform1f(this._uEmissiveFresnelPower,i._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&a.uniform3fv(this._uBaseColor,o.baseColor),this._uMaterialMetallic&&a.uniform1f(this._uMaterialMetallic,o.metallic),this._uMaterialRoughness&&a.uniform1f(this._uMaterialRoughness,o.roughness),this._uMaterialSpecularF0&&a.uniform1f(this._uMaterialSpecularF0,o.specularF0),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const t=i._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(r.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uBaseColorMapMatrix&&a.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const n=i._metallicMap;n&&n._state.texture&&this._uMetallicMap&&(r.bindTexture(this._uMetallicMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicMapMatrix&&a.uniformMatrix4fv(this._uMetallicMapMatrix,!1,n._state.matrix));const l=i._roughnessMap;l&&l._state.texture&&this._uRoughnessMap&&(r.bindTexture(this._uRoughnessMap,l._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uRoughnessMapMatrix&&a.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,l._state.matrix));const c=i._metallicRoughnessMap;c&&c._state.texture&&this._uMetallicRoughnessMap&&(r.bindTexture(this._uMetallicRoughnessMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&a.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,c._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&i._occlusionMap._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&a.uniform3fv(this._uMaterialDiffuse,o.diffuse),this._uMaterialSpecular&&a.uniform3fv(this._uMaterialSpecular,o.specular),this._uMaterialGlossiness&&a.uniform1f(this._uMaterialGlossiness,o.glossiness),this._uMaterialReflectivity&&a.uniform1f(this._uMaterialReflectivity,o.reflectivity),this._uMaterialEmissive&&a.uniform3fv(this._uMaterialEmissive,o.emissive),this._uAlphaModeCutoff&&a.uniform4f(this._uAlphaModeCutoff,1*o.alpha,1===o.alphaMode?1:0,o.alphaCutoff,0);const u=i._diffuseMap;u&&u._state.texture&&this._uDiffuseMap&&(r.bindTexture(this._uDiffuseMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uDiffuseMapMatrix&&a.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,u._state.matrix));const h=i._specularMap;h&&h._state.texture&&this._uSpecularMap&&(r.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularMapMatrix&&a.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const p=i._glossinessMap;p&&p._state.texture&&this._uGlossinessMap&&(r.bindTexture(this._uGlossinessMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uGlossinessMapMatrix&&a.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,p._state.matrix));const y=i._specularGlossinessMap;var A,d,f,I;y&&y._state.texture&&this._uSpecularGlossinessMap&&(r.bindTexture(this._uSpecularGlossinessMap,y._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&a.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,y._state.matrix)),(A=i._emissiveMap)&&A._state.texture&&this._uEmissiveMap&&(r.bindTexture(this._uEmissiveMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uEmissiveMapMatrix&&a.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,A._state.matrix)),(d=i._occlusionMap)&&d._state.texture&&this._uOcclusionMap&&(r.bindTexture(this._uOcclusionMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uOcclusionMapMatrix&&a.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,d._state.matrix)),(f=i._alphaMap)&&f._state.texture&&this._uAlphaMap&&(r.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uAlphaMapMatrix&&a.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(I=i._normalMap)&&I._state.texture&&this._uNormalMap&&(r.bindTexture(this._uNormalMap,I._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%s,e.bindTexture++,this._uNormalMapMatrix&&a.uniformMatrix4fv(this._uNormalMapMatrix,!1,I._state.matrix))}this._lastMaterialId=o.id}if(a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),this._uColorize){const e=l.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(a.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}a.uniform3fv(this._uOffset,l.offset),c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(c.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(c.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(c.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(c.flagsBuf),e.bindArray++),c.indicesBuf&&(c.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=c.id),c.indicesBuf?(a.drawElements(c.primitive,c.indicesBuf.numItems,c.indicesBuf.itemType,0),e.drawElements++):c.positions&&(a.drawArrays(a.TRIANGLES,0,c.positions.numItems),e.drawArrays++),p&&a.depthFunc(a.LESS)},is.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=e._material,i=t._lightsState,a=t._sectionPlanesState,r=e._material._state;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const l=this._program;this._uPositionsDecodeMatrix=l.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=l.getLocation("uvDecodeMatrix"),this._uModelMatrix=l.getLocation("modelMatrix"),this._uModelNormalMatrix=l.getLocation("modelNormalMatrix"),this._uViewMatrix=l.getLocation("viewMatrix"),this._uViewNormalMatrix=l.getLocation("viewNormalMatrix"),this._uProjMatrix=l.getLocation("projMatrix"),this._uGammaFactor=l.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=l.getLocation("logDepthBufFC"));const o=i.lights;let c;for(var u=0,h=o.length;u<h;u++){switch(c=o[u],c.type){case"ambient":this._uLightAmbient[u]=l.getLocation("lightAmbient");break;case"dir":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=null,this._uLightDir[u]=l.getLocation("lightDir"+u);break;case"point":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=null,this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u);break;case"spot":this._uLightColor[u]=l.getLocation("lightColor"+u),this._uLightPos[u]=l.getLocation("lightPos"+u),this._uLightDir[u]=l.getLocation("lightDir"+u),this._uLightAttenuation[u]=l.getLocation("lightAttenuation"+u)}c.castsShadow&&(this._uShadowViewMatrix[u]=l.getLocation("shadowViewMatrix"+u),this._uShadowProjMatrix[u]=l.getLocation("shadowProjMatrix"+u))}i.lightMaps.length>0&&(this._uLightMap="lightMap"),i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(u=0,h=a.sectionPlanes.length;u<h;u++)this._uSectionPlanes.push({active:l.getLocation("sectionPlaneActive"+u),pos:l.getLocation("sectionPlanePos"+u),dir:l.getLocation("sectionPlaneDir"+u)});switch(this._uPointSize=l.getLocation("pointSize"),r.type){case"LambertMaterial":this._uMaterialColor=l.getLocation("materialColor"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=l.getLocation("materialAmbient"),this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=l.getLocation("materialShininess"),n._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=l.getLocation("ambientMapMatrix")),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=l.getLocation("reflectivityMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=l.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=l.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=l.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=l.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=l.getLocation("diffuseFresnelPower")),n._specularFresnel&&(this._uSpecularFresnelEdgeBias=l.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=l.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=l.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=l.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=l.getLocation("specularFresnelPower")),n._alphaFresnel&&(this._uAlphaFresnelEdgeBias=l.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=l.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=l.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=l.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=l.getLocation("alphaFresnelPower")),n._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=l.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=l.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=l.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=l.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=l.getLocation("reflectivityFresnelPower")),n._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=l.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=l.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=l.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=l.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=l.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=l.getLocation("materialBaseColor"),this._uMaterialMetallic=l.getLocation("materialMetallic"),this._uMaterialRoughness=l.getLocation("materialRoughness"),this._uMaterialSpecularF0=l.getLocation("materialSpecularF0"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=l.getLocation("baseColorMapMatrix")),n._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=l.getLocation("metallicMapMatrix")),n._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=l.getLocation("roughnessMapMatrix")),n._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=l.getLocation("metallicRoughnessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=l.getLocation("materialDiffuse"),this._uMaterialSpecular=l.getLocation("materialSpecular"),this._uMaterialGlossiness=l.getLocation("materialGlossiness"),this._uMaterialReflectivity=l.getLocation("reflectivityFresnel"),this._uMaterialEmissive=l.getLocation("materialEmissive"),this._uAlphaModeCutoff=l.getLocation("materialAlphaModeCutoff"),n._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=l.getLocation("diffuseMapMatrix")),n._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=l.getLocation("specularMapMatrix")),n._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=l.getLocation("glossinessMapMatrix")),n._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=l.getLocation("materialSpecularGlossinessMapMatrix")),n._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=l.getLocation("emissiveMapMatrix")),n._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=l.getLocation("occlusionMapMatrix")),n._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=l.getLocation("alphaMapMatrix")),n._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=l.getLocation("normalMapMatrix"))}this._aPosition=l.getAttribute("position"),this._aNormal=l.getAttribute("normal"),this._aUV=l.getAttribute("uv"),this._aColor=l.getAttribute("color"),this._aFlags=l.getAttribute("flags"),this._uClippable=l.getLocation("clippable"),this._uColorize=l.getLocation("colorize"),this._uOffset=l.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},is.prototype._bindProgram=function(e){const t=ge.MAX_TEXTURE_UNITS,s=this._scene,n=s.canvas.gl,i=s._lightsState,a=s.camera.project;let r;const l=this._program;if(l.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,n.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}for(var o=0,c=i.lights.length;o<c;o++)if(r=i.lights[o],this._uLightAmbient[o])n.uniform4f(this._uLightAmbient[o],r.color[0],r.color[1],r.color[2],r.intensity);else if(this._uLightColor[o]&&n.uniform4f(this._uLightColor[o],r.color[0],r.color[1],r.color[2],r.intensity),this._uLightPos[o]&&(n.uniform3fv(this._uLightPos[o],r.pos),this._uLightAttenuation[o]&&n.uniform1f(this._uLightAttenuation[o],r.attenuation)),this._uLightDir[o]&&n.uniform3fv(this._uLightDir[o],r.dir),r.castsShadow){this._uShadowViewMatrix[o]&&n.uniformMatrix4fv(this._uShadowViewMatrix[o],!1,r.getShadowViewMatrix()),this._uShadowProjMatrix[o]&&n.uniformMatrix4fv(this._uShadowProjMatrix[o],!1,r.getShadowProjMatrix());const s=r.getShadowRenderBuf();s&&(l.bindTexture("shadowMap"+o,s.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}i.lightMaps.length>0&&i.lightMaps[0].texture&&this._uLightMap&&(l.bindTexture(this._uLightMap,i.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),i.reflectionMaps.length>0&&i.reflectionMaps[0].texture&&this._uReflectionMap&&(l.bindTexture(this._uReflectionMap,i.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};class rs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._lightsState,n=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),i=t._sectionPlanesState.sectionPlanes.length>0,a=!!e._geometry._state.compressGeometry,r=e._state.billboard,l=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// EmphasisFillShaderSource vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 colorize;"),o.push("uniform vec3 offset;"),a&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");if(o.push("uniform vec4 lightAmbient;"),o.push("uniform vec4 fillColor;"),n){o.push("in vec3 normal;"),o.push("uniform mat4 modelNormalMatrix;"),o.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&o.push("uniform vec3 lightPos"+e+";"))}a&&(o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"))}o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),a&&o.push("localPosition = positionsDecodeMatrix * localPosition;");n&&(a?o.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):o.push("vec4 localNormal = vec4(normal, 0.0); "),o.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),o.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),l&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),n&&(o.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),o.push("billboard(modelNormalMatrix2);"),o.push("billboard(viewNormalMatrix2);"),o.push("billboard(modelViewNormalMatrix);")),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n&&o.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),n)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?o.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}o.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),i&&o.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&o.push("gl_PointSize = pointSize;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Lambertian drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}"points"===e._geometry._state.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push(" discard;"),a.push("}"));t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const ls=new e({}),os=h.vec3(),cs=function(e,t){this.id=ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new rs(t),this._allocate(t)},us={};cs.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=us[t];return s||(s=new cs(t,e),us[t]=s,d.memory.programs++),s._useCount++,s},cs.prototype.put=function(){0==--this._useCount&&(ls.removeItem(this.id),this._program&&this._program.destroy(),delete us[this._hash],d.memory.programs--)},cs.prototype.webglContextRestored=function(){this._program=null},cs.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl,r=0===s?t._xrayMaterial._state:1===s?t._highlightMaterial._state:t._selectedMaterial._state,l=t._state,o=t._geometry._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):i.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.viewNormalMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,c?k(n.dist,n.dir,c,os):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}if(r.id!==this._lastMaterialId){const t=r.fillColor,s=r.backfaces;e.backfaces!==s&&(s?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=s),a.uniform4f(this._uFillColor,t[0],t[1],t[2],r.fillAlpha),this._lastMaterialId=r.id}a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uModelNormalMatrix&&a.uniformMatrix4fv(this._uModelNormalMatrix,a.FALSE,t.worldNormalMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),o.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,o.positionsDecodeMatrix),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(o.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(o.normalsBuf),e.bindArray++),o.indicesBuf?(o.indicesBuf.bind(),e.bindArray++):o.positionsBuf,this._lastGeometryId=o.id),o.indicesBuf?(a.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positionsBuf&&(a.drawArrays(a.TRIANGLES,0,o.positionsBuf.numItems),e.drawArrays++)},cs.prototype._allocate=function(e){const t=e.scene,s=t._lightsState,n=t._sectionPlanesState,i=t.canvas.gl;if(this._program=new Be(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uModelMatrix=a.getLocation("modelMatrix"),this._uModelNormalMatrix=a.getLocation("modelNormalMatrix"),this._uViewMatrix=a.getLocation("viewMatrix"),this._uViewNormalMatrix=a.getLocation("viewNormalMatrix"),this._uProjMatrix=a.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=s.lights.length;e<t;e++){switch(s.lights[e].type){case"ambient":this._uLightAmbient[e]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=a.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=a.getLocation("lightColor"+e),this._uLightPos[e]=a.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=a.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+e),pos:a.getLocation("sectionPlanePos"+e),dir:a.getLocation("sectionPlaneDir"+e)});this._uFillColor=a.getLocation("fillColor"),this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._uClippable=a.getLocation("clippable"),this._uGammaFactor=a.getLocation("gammaFactor"),this._uOffset=a.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},cs.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t._lightsState,i=t.camera,a=i.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,s.uniformMatrix4fv(this._uViewNormalMatrix,!1,i.normalMatrix),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];this._uLightAmbient[e]?s.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor)};class hs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Edges drawing vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec4 edgeColor;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));s&&r.push("out vec4 vWorldPosition;");r.push("out vec4 vColor;"),("spherical"===i||"cylindrical"===i)&&(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.push("vColor = edgeColor;"),s&&r.push("vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=e.scene._sectionPlanesState,n=e.scene.gammaOutput,i=s.sectionPlanes.length>0,a=[];a.push("#version 300 es"),a.push("// Edges drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;"));n&&(a.push("uniform float gammaFactor;"),a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}"));if(i){a.push("in vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push("if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?a.push("outColor = linearToGamma(vColor, gammaFactor);"):a.push("outColor = vColor;");return a.push("}"),a}(e)}}const ps=new e({}),As=h.vec3(),ds=function(e,t){this.id=ps.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new hs(t),this._allocate(t)},fs={};ds.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=fs[t];return s||(s=new ds(t,e),fs[t]=s,d.memory.programs++),s._useCount++,s},ds.prototype.put=function(){0==--this._useCount&&(ps.removeItem(this.id),this._program&&this._program.destroy(),delete fs[this._hash],d.memory.programs--)},ds.prototype.webglContextRestored=function(){this._program=null},ds.prototype.drawMesh=function(e,t,s){this._program||this._allocate(t);const n=this._scene,i=n.camera,a=n.canvas.gl;let r;const l=t._state,o=t._geometry,c=o._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(l.originHash,u):i.viewMatrix),l.clippable){const e=n._sectionPlanesState.sectionPlanes.length;if(e>0){const s=n._sectionPlanesState.sectionPlanes,i=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const n=i.sectionPlanesActivePerLayer[t];if(a.uniform1i(e.active,n?1:0),n){const n=s[t];a.uniform3fv(e.pos,u?k(n.dist,n.dir,u,As):n.pos),a.uniform3fv(e.dir,n.dir)}}}}}switch(s){case 0:r=t._xrayMaterial._state;break;case 1:r=t._highlightMaterial._state;break;case 2:r=t._selectedMaterial._state;break;default:r=t._edgeMaterial._state}if(r.id!==this._lastMaterialId){const t=r.backfaces;if(e.backfaces!==t&&(t?a.disable(a.CULL_FACE):a.enable(a.CULL_FACE),e.backfaces=t),e.lineWidth!==r.edgeWidth&&(a.lineWidth(r.edgeWidth),e.lineWidth=r.edgeWidth),this._uEdgeColor){const e=r.edgeColor,t=r.edgeAlpha;a.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=r.id}let h;a.uniformMatrix4fv(this._uModelMatrix,a.FALSE,t.worldMatrix),this._uClippable&&a.uniform1i(this._uClippable,l.clippable),a.uniform3fv(this._uOffset,l.offset),c.primitive===a.TRIANGLES?h=o._getEdgeIndices():c.primitive===a.LINES&&(h=c.indicesBuf),h&&(c.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,c.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(c.positionsBuf,c.compressGeometry?a.UNSIGNED_SHORT:a.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=c.id),a.drawElements(a.LINES,h.numItems,h.itemType,0),e.drawElements++)},ds.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uModelMatrix=i.getLocation("modelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=n.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+e),pos:i.getLocation("sectionPlanePos"+e),dir:i.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=i.getLocation("edgeColor"),this._aPosition=i.getAttribute("position"),this._uClippable=i.getLocation("clippable"),this._uGammaFactor=i.getLocation("gammaFactor"),this._uOffset=i.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ds.prototype._bindProgram=function(e){const t=this._program,s=this._scene,n=s.canvas.gl,i=s.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&n.uniform1f(this._uGammaFactor,s.gammaFactor)};class Is{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh picking vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("out vec4 vViewPosition;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==i&&"cylindrical"!==i||(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"));r.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(i.push("uniform vec4 pickColor;"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = pickColor; "),i.push("}"),i}(e)}}const ys=h.vec3(),ms=function(e,t){this._hash=e,this._shaderSource=new Is(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},vs={};ms.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=vs[t];if(!s){if(s=new ms(t,e),s.errors)return console.log(s.errors.join("\n")),null;vs[t]=s,d.memory.programs++}return s._useCount++,s},ms.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete vs[this._hash],d.memory.programs--)},ms.prototype.webglContextRestored=function(){this._program=null},ms.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(i.originHash,l):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?k(s.dist,s.dir,l,ys):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}if(a.id!==this._lastMaterialId){const t=a.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=a.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=a.id}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id);var o=t._state.pickID;const c=o>>24&255,u=o>>16&255,h=o>>8&255,p=255&o;n.uniform4f(this._uPickColor,p/255,h/255,u/255,c/255),n.uniform2fv(this._uPickClipPos,e.pickClipPos),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},ms.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uPickColor=n.getLocation("pickColor"),this._uPickClipPos=n.getLocation("pickClipPos"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},ms.prototype._bindProgram=function(e){const t=this._scene,s=t.canvas.gl,n=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class ws{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=[];i.push("#version 300 es"),i.push("// Surface picking vertex shader"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform vec3 offset;"),s&&(i.push("uniform bool clippable;"),i.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"));i.push("uniform vec2 pickClipPos;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy -= pickClipPos;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("out vec4 vColor;"),n&&i.push("uniform mat4 positionsDecodeMatrix;");i.push("void main(void) {"),i.push("vec4 localPosition = vec4(position, 1.0); "),n&&i.push("localPosition = positionsDecodeMatrix * localPosition;");i.push(" vec4 worldPosition = modelMatrix * localPosition; "),i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),s&&i.push(" vWorldPosition = worldPosition;");i.push(" vColor = color;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Surface picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0;e<s.sectionPlanes.length;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push(" outColor = vColor;"),i.push("}"),i}(e)}}const gs=h.vec3(),Es=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ws(t),this._allocate(t)},Ts={};Es.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let s=Ts[t];if(!s){if(s=new Es(t,e),s.errors)return console.log(s.errors.join("\n")),null;Ts[t]=s,d.memory.programs++}return s._useCount++,s},Es.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ts[this._hash],d.memory.programs--)},Es.prototype.webglContextRestored=function(){this._program=null},Es.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._state,a=t._material._state,r=t._geometry,l=t._geometry._state,o=t.origin,c=a.backfaces,u=a.frontface,h=s.camera.project,p=r._getPickTrianglePositions(),A=r._getPickTriangleColors();if(this._program.bind(),e.useProgram++,s.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}if(n.uniformMatrix4fv(this._uViewMatrix,!1,o?e.getRTCPickViewMatrix(i.originHash,o):e.pickViewMatrix),i.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,o?k(s.dist,s.dir,o,gs):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.logarithmicDepthBufferEnabled&&n.uniform1f(this._uZFar,s.camera.project.far),e.backfaces!==c&&(c?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=c),e.frontface!==u&&(u?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=u),n.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(p,l.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT)):this._aPosition.bindArrayBuffer(p),n.uniform2fv(this._uPickClipPos,e.pickClipPos),A.bind(),n.enableVertexAttribArray(this._aColor.location),n.vertexAttribPointer(this._aColor.location,A.itemSize,A.itemType,!0,0,0),n.drawArrays(l.primitive,0,p.numItems/3)},Es.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._aColor=n.getAttribute("color"),this._uPickClipPos=n.getLocation("pickClipPos"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"))};class bs{constructor(e){this.vertex=function(e){const t=e.scene,s=t._sectionPlanesState.sectionPlanes.length>0,n=!!e._geometry._state.compressGeometry,i=e._state.billboard,a=e._state.stationary,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),n&&r.push("uniform mat4 positionsDecodeMatrix;");s&&r.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));"spherical"!==i&&"cylindrical"!==i||(r.push("void billboard(inout mat4 mat) {"),r.push(" mat[0][0] = 1.0;"),r.push(" mat[0][1] = 0.0;"),r.push(" mat[0][2] = 0.0;"),"spherical"===i&&(r.push(" mat[1][0] = 0.0;"),r.push(" mat[1][1] = 1.0;"),r.push(" mat[1][2] = 0.0;")),r.push(" mat[2][0] = 0.0;"),r.push(" mat[2][1] = 0.0;"),r.push(" mat[2][2] =1.0;"),r.push("}"));r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),n&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("mat4 viewMatrix2 = viewMatrix;"),r.push("mat4 modelMatrix2 = modelMatrix;"),a&&r.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===i||"cylindrical"===i?(r.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),r.push("billboard(modelMatrix2);"),r.push("billboard(viewMatrix2);"),r.push("billboard(modelViewMatrix);"),r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(r.push("worldPosition = modelMatrix2 * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&r.push(" vWorldPosition = worldPosition;");r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];i.push("#version 300 es"),i.push("// Mesh occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"));if(n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&i.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return i.push("}"),i}(e)}}const Ds=h.vec3(),Ps=function(e,t){this._hash=e,this._shaderSource=new bs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Rs={};Ps.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let s=Rs[t];if(!s){if(s=new Ps(t,e),s.errors)return console.log(s.errors.join("\n")),null;Rs[t]=s,d.memory.programs++}return s._useCount++,s},Ps.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Rs[this._hash],d.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene,n=s.canvas.gl,i=t._material._state,a=t._state,r=t._geometry._state,l=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),i.id!==this._lastMaterialId){const t=i.backfaces;e.backfaces!==t&&(t?n.disable(n.CULL_FACE):n.enable(n.CULL_FACE),e.backfaces=t);const s=i.frontface;e.frontface!==s&&(s?n.frontFace(n.CCW):n.frontFace(n.CW),e.frontface=s),this._lastMaterialId=i.id}const o=s.camera;if(n.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCViewMatrix(a.originHash,l):o.viewMatrix),a.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,a=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e){const s=a.sectionPlanesActivePerLayer[t];if(n.uniform1i(e.active,s?1:0),s){const s=i[t];n.uniform3fv(e.pos,l?k(s.dist,s.dir,l,Ds):s.pos),n.uniform3fv(e.dir,s.dir)}}}}}n.uniformMatrix4fv(this._uProjMatrix,!1,o._project._state.matrix),n.uniformMatrix4fv(this._uModelMatrix,n.FALSE,t.worldMatrix),this._uClippable&&n.uniform1i(this._uClippable,t._state.clippable),n.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?n.UNSIGNED_SHORT:n.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=r.id),r.indicesBuf?(n.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&n.drawArrays(n.TRIANGLES,0,r.positions.numItems)},Ps.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Ps.prototype._bindProgram=function(e){const t=this._scene,s=t.camera.project,n=t.canvas.gl;if(this._program.bind(),e.useProgram++,n.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Cs{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,n=[];n.push("// Mesh shadow vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 shadowViewMatrix;"),n.push("uniform mat4 shadowProjMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t&&n.push("out vec4 vWorldPosition;");n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("worldPosition = modelMatrix * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&n.push("vWorldPosition = worldPosition;");return n.push(" gl_Position = shadowProjMatrix * viewPosition;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const s=t._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("// Mesh shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),n){i.push("uniform bool clippable;"),i.push("in vec4 vWorldPosition;");for(var a=0;a<s.sectionPlanes.length;a++)i.push("uniform bool sectionPlaneActive"+a+";"),i.push("uniform vec3 sectionPlanePos"+a+";"),i.push("uniform vec3 sectionPlaneDir"+a+";")}if(i.push("vec4 encodeFloat( const in float depth ) {"),i.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push(" vec4 comp = fract(depth * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push("if (clippable) {"),i.push(" float dist = 0.0;");for(a=0;a<s.sectionPlanes.length;a++)i.push("if (sectionPlaneActive"+a+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+a+".xyz, vWorldPosition.xyz - sectionPlanePos"+a+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { discard; }"),i.push("}")}return i.push("outColor = encodeFloat(gl_FragCoord.z);"),i.push("}"),i}(e)}}const _s=function(e,t){this._hash=e,this._shaderSource=new Cs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Bs={};_s.get=function(e){const t=e.scene,s=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let n=Bs[s];if(!n){if(n=new _s(s,e),n.errors)return console.log(n.errors.join("\n")),null;Bs[s]=n,d.memory.programs++}return n._useCount++,n},_s.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Bs[this._hash],d.memory.programs--)},_s.prototype.webglContextRestored=function(){this._program=null},_s.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const s=this._scene.canvas.gl,n=t._material._state,i=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.id!==this._lastMaterialId){const t=n.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=n.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),e.lineWidth!==n.lineWidth&&(s.lineWidth(n.lineWidth),e.lineWidth=n.lineWidth),this._uPointSize&&s.uniform1i(this._uPointSize,n.pointSize),this._lastMaterialId=n.id}if(s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),i.combineGeometry){const n=t.vertexBufs;n.id!==this._lastVertexBufsId&&(n.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),this._lastVertexBufsId=n.id)}this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),i.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,i.positionsDecodeMatrix),i.combineGeometry?i.indicesBufCombined&&(i.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(i.positionsBuf,i.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),i.indicesBuf&&(i.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=i.id),i.combineGeometry?i.indicesBufCombined&&(s.drawElements(i.primitive,i.indicesBufCombined.numItems,i.indicesBufCombined.itemType,0),e.drawElements++):i.indicesBuf?(s.drawElements(i.primitive,i.indicesBuf.numItems,i.indicesBuf.itemType,0),e.drawElements++):i.positions&&(s.drawArrays(s.TRIANGLES,0,i.positions.numItems),e.drawArrays++)},_s.prototype._allocate=function(e){const t=e.scene,s=t.canvas.gl;if(this._program=new Be(s,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,s=t._sectionPlanesState.sectionPlanes.length;e<s;e++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+e),pos:n.getLocation("sectionPlanePos"+e),dir:n.getLocation("sectionPlaneDir"+e)});this._aPosition=n.getAttribute("position"),this._uClippable=n.getLocation("clippable"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},_s.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,s=t.canvas.gl,n=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),s.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,n.sectionPlanes.length>0){let e,t,i,a,r;for(let l=0,o=this._uSectionPlanes.length;l<o;l++)e=this._uSectionPlanes[l],t=e.active,i=n.sectionPlanes[l],t&&s.uniform1i(t,i.active),a=e.pos,a&&s.uniform3fv(e.pos,i.pos),r=e.dir,r&&s.uniform3fv(e.dir,i.dir)}};class Os{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Ss=h.OBB3(),Ns=h.vec4(),xs=h.vec4(),Ls=h.vec4(),Ms=h.vec3([1,0,0]),Fs=h.vec3([0,1,0]),Hs=h.vec3([0,0,1]),Us=h.vec3(3),Gs=h.vec3(3),js=h.identityMat4();class Vs extends _{constructor(e,t={}){super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Os,this._state=new Je({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:h.vec3(),origin:null,originHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._worldMatrix=h.identityMat4(),this._worldNormalMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const s=t.origin||t.rtcCenter;if(s&&(this._state.origin=h.vec3(s),this._state.originHash=s.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=h.identityMat4()),this.__localMatrix.set(e||js),h.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=h.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const s=!!e;this.scene._objectColorizeUpdated(this,s),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const s=null!=e;t[3]=s?e:1,this.scene._objectOpacityUpdated(this,s),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=is.get(this),this._emphasisFillRenderer=cs.get(this),this._emphasisEdgesRenderer=ds.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=ms.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=Ps.get(this))}}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=h.mat4()),h.transposeMat4(this._worldMatrix,this._worldNormalMatrix),h.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),s.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],s=this._state;return s.stationary&&t.push("/s"),"none"===s.billboard?t.push("/n"):"spherical"===s.billboard?t.push("/s"):"cylindrical"===s.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){h.transformOBB3(e,this._geometry.obb,Ss),h.OBB3ToAABB3(Ss,t);const s=this._state.offset;if(t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[0],t[4]+=s[1],t[5]+=s[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Ns[0]=e[0],Ns[1]=e[1],Ns[2]=e[2],Ns[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ns,xs),h.mulQuaternions(this.quaternion,xs,Ls),this.quaternion=Ls,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ns[0]=e[0],Ns[1]=e[1],Ns[2]=e[2],Ns[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ns,xs),h.mulQuaternions(xs,this.quaternion,xs),this}rotateX(e){return this.rotate(Ms,e)}rotateY(e){return this.rotate(Fs,e)}rotateZ(e){return this.rotate(Hs,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Us),h.mulVec3Scalar(Us,t,Gs),h.addVec3(this.position,Gs,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ms,e)}translateY(e){return this.translate(Fs,e)}translateZ(e){return this.translate(Hs,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let s=0;s<t;s++){const t=e[s],n=this.renderFlags;if(t.active)if(this._state.origin){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const i=0===e;n.sectionPlanesActivePerLayer[s]=i}else n.sectionPlanesActivePerLayer[s]=!0;else n.sectionPlanesActivePerLayer[s]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=is.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=cs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=cs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=cs.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=ds.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=Ps.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=_s.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=ms.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=Es.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,s){ks(this,e,t,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const ks=function(){const e=h.vec3(),t=h.vec3(),s=h.vec3(),n=h.vec3(),i=h.vec3(),a=h.vec3(),r=h.vec4(),l=h.vec3(),o=h.vec3(),c=h.vec3(),u=h.vec3(),p=h.vec3(),A=h.vec3(),d=h.vec3(),f=h.vec3(),I=h.vec3(),y=h.vec4(),m=h.vec4(),v=h.vec4(),w=h.vec3(),g=h.vec3(),E=h.vec3(),T=h.vec3(),b=h.vec3(),D=h.vec3(),P=h.vec3(),R=h.vec3(),C=h.vec3(),_=h.vec3(),B=h.vec3();return function(O,S,N,x){var L=x.primIndex;if(null!=L&&L>-1){const U=O.geometry._state,j=O.scene,V=j.camera,k=j.canvas;if("triangles"===U.primitiveName){x.primitive="triangle";const j=L,Q=U.indices,W=U.positions;let z,K,Y;if(Q){var M=Q[j+0],F=Q[j+1],H=Q[j+2];a[0]=M,a[1]=F,a[2]=H,x.indices=a,z=3*M,K=3*F,Y=3*H}else z=3*j,K=z+3,Y=K+3;if(s[0]=W[z+0],s[1]=W[z+1],s[2]=W[z+2],n[0]=W[K+0],n[1]=W[K+1],n[2]=W[K+2],i[0]=W[Y+0],i[1]=W[Y+1],i[2]=W[Y+2],U.compressGeometry){const e=U.positionsDecodeMatrix;e&&(Bt.decompressPosition(s,e,s),Bt.decompressPosition(n,e,n),Bt.decompressPosition(i,e,i))}x.canvasPos?h.canvasPosToLocalRay(k.canvas,O.origin?G(S,O.origin):S,N,O.worldMatrix,x.canvasPos,e,t):x.origin&&x.direction&&h.worldRayToLocalRay(O.worldMatrix,x.origin,x.direction,e,t),h.normalizeVec3(t),h.rayPlaneIntersect(e,t,s,n,i,r),x.localPos=r,x.position=r,y[0]=r[0],y[1]=r[1],y[2]=r[2],y[3]=1,h.transformVec4(O.worldMatrix,y,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],x.canvasPos&&O.origin&&(l[0]+=O.origin[0],l[1]+=O.origin[1],l[2]+=O.origin[2]),x.worldPos=l,h.transformVec4(V.matrix,m,v),o[0]=v[0],o[1]=v[1],o[2]=v[2],x.viewPos=o,h.cartesianToBarycentric(r,s,n,i,c),x.bary=c;const X=U.normals;if(X){if(U.compressGeometry){const e=3*M,t=3*F,s=3*H;Bt.decompressNormal(X.subarray(e,e+2),u),Bt.decompressNormal(X.subarray(t,t+2),p),Bt.decompressNormal(X.subarray(s,s+2),A)}else u[0]=X[z],u[1]=X[z+1],u[2]=X[z+2],p[0]=X[K],p[1]=X[K+1],p[2]=X[K+2],A[0]=X[Y],A[1]=X[Y+1],A[2]=X[Y+2];const e=h.addVec3(h.addVec3(h.mulVec3Scalar(u,c[0],w),h.mulVec3Scalar(p,c[1],g),E),h.mulVec3Scalar(A,c[2],T),b);x.worldNormal=h.normalizeVec3(h.transformVec3(O.worldNormalMatrix,e,D))}const q=U.uv;if(q){if(d[0]=q[2*M],d[1]=q[2*M+1],f[0]=q[2*F],f[1]=q[2*F+1],I[0]=q[2*H],I[1]=q[2*H+1],U.compressGeometry){const e=U.uvDecodeMatrix;e&&(Bt.decompressUV(d,e,d),Bt.decompressUV(f,e,f),Bt.decompressUV(I,e,I))}x.uv=h.addVec3(h.addVec3(h.mulVec2Scalar(d,c[0],P),h.mulVec2Scalar(f,c[1],R),C),h.mulVec2Scalar(I,c[2],_),B)}}}}}();function Qs(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let s=e.radiusBottom||1;s<0&&(console.error("negative radiusBottom not allowed - will invert"),s*=-1);let n=e.height||1;n<0&&(console.error("negative height not allowed - will invert"),n*=-1);let i=e.radialSegments||32;i<0&&(console.error("negative radialSegments not allowed - will invert"),i*=-1),i<3&&(i=3);let a=e.heightSegments||1;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a<1&&(a=1);const r=!!e.openEnded;let l=e.center;const o=l?l[0]:0,c=l?l[1]:0,u=l?l[2]:0,h=n/2,p=n/a,A=2*Math.PI/i,d=1/i,f=(t-s)/a,I=[],y=[],v=[],w=[];let g,E,T,b,D,P,R,C,_,B,O;const S=(90-180*Math.atan(n/(s-t))/Math.PI)/90;for(g=0;g<=a;g++)for(D=t-g*f,P=h-g*p,E=0;E<=i;E++)T=Math.sin(E*A),b=Math.cos(E*A),y.push(D*T),y.push(S),y.push(D*b),v.push(E*d),v.push(1*g/a),I.push(D*T+o),I.push(P+c),I.push(D*b+u);for(g=0;g<a;g++)for(E=0;E<=i;E++)R=g*(i+1)+E,C=R+i,w.push(R),w.push(C),w.push(C+1),w.push(R),w.push(C+1),w.push(R+1);if(!r&&t>0){for(_=I.length/3,y.push(0),y.push(1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(h+c),I.push(0+u),E=0;E<=i;E++)T=Math.sin(E*A),b=Math.cos(E*A),B=.5*Math.sin(E*A)+.5,O=.5*Math.cos(E*A)+.5,y.push(t*T),y.push(1),y.push(t*b),v.push(B),v.push(O),I.push(t*T+o),I.push(h+c),I.push(t*b+u);for(E=0;E<i;E++)l=_,R=_+1+E,w.push(R),w.push(R+1),w.push(l)}if(!r&&s>0){for(_=I.length/3,y.push(0),y.push(-1),y.push(0),v.push(.5),v.push(.5),I.push(0+o),I.push(0-h+c),I.push(0+u),E=0;E<=i;E++)T=Math.sin(E*A),b=Math.cos(E*A),B=.5*Math.sin(E*A)+.5,O=.5*Math.cos(E*A)+.5,y.push(s*T),y.push(-1),y.push(s*b),v.push(B),v.push(O),I.push(s*T+o),I.push(0-h+c),I.push(s*b+u);for(E=0;E<i;E++)l=_,R=_+1+E,w.push(l),w.push(R+1),w.push(R)}return m.apply(e,{positions:I,normals:y,uv:v,indices:w})}function Ws(e={}){const t=e.lod||1,s=e.center?e.center[0]:0,n=e.center?e.center[1]:0,i=e.center?e.center[2]:0;let a=e.radius||1;a<0&&(console.error("negative radius not allowed - will invert"),a*=-1);let r=e.heightSegments||18;r<0&&(console.error("negative heightSegments not allowed - will invert"),r*=-1),r=Math.floor(t*r),r<18&&(r=18);let l=e.widthSegments||18;l<0&&(console.error("negative widthSegments not allowed - will invert"),l*=-1),l=Math.floor(t*l),l<18&&(l=18);const o=[],c=[],u=[],h=[];let p,A,d,f,I,y,v,w,g,E,T,b,D,P,R;for(p=0;p<=r;p++)for(d=p*Math.PI/r,f=Math.sin(d),I=Math.cos(d),A=0;A<=l;A++)y=2*A*Math.PI/l,v=Math.sin(y),w=Math.cos(y),g=w*f,E=I,T=v*f,b=1-A/l,D=p/r,c.push(g),c.push(E),c.push(T),u.push(b),u.push(D),o.push(s+a*g),o.push(n+a*E),o.push(i+a*T);for(p=0;p<r;p++)for(A=0;A<l;A++)P=p*(l+1)+A,R=P+l+1,h.push(P+1),h.push(R+1),h.push(R),h.push(P+1),h.push(R),h.push(P);return m.apply(e,{positions:o,normals:c,uv:u,indices:h})}const zs={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function Ks(e={}){var t=e.origin||[0,0,0],s=t[0],n=t[1],i=t[2],a=e.size||1,r=[],l=[],o=e.text;m.isNumeric(o)&&(o=""+o);for(var c,u,h,p,A,d,f,I,y,v=(o||"").split("\n"),w=0,g=0,E=.04,T=0;T<v.length;T++){c=0,h=(u=v[T]).length;for(var b=0;b<h;b++)if(p=zs[u.charAt(b)]){A=1,d=-1,f=-1,I=p.points.length;for(var D=0;D<I;D++)-1!==(y=p.points[D])[0]||-1!==y[1]?(r.push(c+y[0]*a*E+s),r.push(g+y[1]*a*E+n),r.push(0+i),-1===d?d=w:(-1===f||(d=f),f=w),w++,A?A=!1:(l.push(d),l.push(f))):A=1;c+=p.width*E*a}g-=35*E*a}return m.apply(e,{primitive:"lines",positions:r,indices:l})}h.vec3();class Ys extends _{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new Je({active:!0,pos:h.vec3(),dir:h.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-h.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const Xs=h.vec4(4),qs=h.vec4(),Js=h.vec4(),Zs=h.vec3([1,0,0]),$s=h.vec3([0,1,0]),en=h.vec3([0,0,1]),tn=h.vec3(3),sn=h.vec3(3),nn=h.identityMat4();class an extends _{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=h.vec3(),this._quaternion=h.identityQuaternion(),this._rotation=h.vec3(),this._position=h.vec3(),this._offset=h.vec3(),this._localMatrix=h.identityMat4(),this._worldMatrix=h.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let s=0,n=e.length;s<n;s++)this.addChild(e[s],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=h.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,s=this._children.length;t<s;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,s=this._children.length;e<s;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,s=this._children.length;t<s;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,s=this._children.length;t<s;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)h.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,s=e.length;t<s;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,s=e._children.length;t<s;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=h.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;h.collapseAABB3(this._aabb);for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e.collidable&&h.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+m.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,s=this._children.length;t<s;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,s=this._children.length;t<s;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(m.isNumeric(e)||m.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+m.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||nn),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=h.identityMat4()),h.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return Xs[0]=e[0],Xs[1]=e[1],Xs[2]=e[2],Xs[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Xs,qs),h.mulQuaternions(this.quaternion,qs,Js),this.quaternion=Js,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Xs[0]=e[0],Xs[1]=e[1],Xs[2]=e[2],Xs[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Xs,qs),h.mulQuaternions(qs,this.quaternion,qs),this}rotateX(e){return this.rotate(Zs,e)}rotateY(e){return this.rotate($s,e)}rotateZ(e){return this.rotate(en,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,tn),h.mulVec3Scalar(tn,t,sn),h.addVec3(this.position,sn,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Zs,e)}translateY(e){return this.translate($s,e)}translateZ(e){return this.translate(en,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let s=0,n=e.length;s<n;s++)t=e[s],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}class rn extends Lt{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"LambertMaterial",ambient:h.vec3([1,1,1]),color:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const ln={opaque:0,mask:1,blend:2},on=["opaque","mask","blend"];class cn extends Lt{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"MetallicMaterial",baseColor:h.vec4([1,1,1]),emissive:h.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=ln[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return on[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const un={opaque:0,mask:1,blend:2},hn=["opaque","mask","blend"];class pn extends Lt{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new Je({type:"SpecularMaterial",diffuse:h.vec3([1,1,1]),emissive:h.vec3([0,0,0]),specular:h.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=un[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return hn[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}function An(e,t,s=null){let n;const i=t;if(1009===i)return e.UNSIGNED_BYTE;if(1017===i)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===i)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(1012===i)return e.UNSIGNED_SHORT;if(1013===i)return e.INT;if(1014===i)return e.UNSIGNED_INT;if(1015===i)return e.FLOAT;if(1016===i)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1023===i)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(1026===i)return e.DEPTH_COMPONENT;if(1027===i)return e.DEPTH_STENCIL;if(1028===i)return e.RED;if(1022===i)return e.RGBA;if(1029===i)return e.RED_INTEGER;if(1030===i)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(33776===i||33777===i||33778===i||33779===i)if(3001===s){const t=Ke(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===i)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===i)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(n=Ke(e,"WEBGL_compressed_texture_s3tc"),null===n)return null;if(33776===i)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===i)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===i)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===i)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===i||35841===i||35842===i||35843===i){const t=Ke(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===i)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===i)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===i){const t=Ke(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===i||37496===i){const t=Ke(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===i)return 3001===s?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===i||37809===i||37810===i||37811===i||37812===i||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){const t=Ke(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return 3001===s?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===i){const t=Ke(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===i)return 3001===s?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===i?e.UNSIGNED_INT_24_8:1e3===i?e.REPEAT:1001===i?e.CLAMP_TO_EDGE:1004===i||1005===i?e.NEAREST_MIPMAP_LINEAR:1007===i?e.LINEAR_MIPMAP_NEAREST:1008===i?e.LINEAR_MIPMAP_LINEAR:1003===i?e.NEAREST:1006===i?e.LINEAR:null}const dn=new Uint8Array([0,0,0,1]);class fn{constructor({gl:e,target:t,format:s,type:n,wrapS:i,wrapT:a,wrapR:r,encoding:l,preloadColor:o,premultiplyAlpha:c,flipY:u}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!u,this.unpackAlignment=4,this.wrapS=i||1e3,this.wrapT=a||1e3,this.wrapR=r||1e3,this.encoding=l||3001,this.texture=e.createTexture(),o&&this.setPreloadColor(o),this.allocated=!0}setPreloadColor(e){e?(dn[0]=Math.floor(255*e[0]),dn[1]=Math.floor(255*e[1]),dn[2]=Math.floor(255*e[2]),dn[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(dn[0]=0,dn[1]=0,dn[2]=0,dn[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let s=0,n=e.length;s<n;s++)t.texImage2D(e[s],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,dn)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,dn);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const s=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let n=!1;s.bindTexture(this.target,this.texture);const i=s.getParameter(s.UNPACK_FLIP_Y_WEBGL);s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY);const a=s.getParameter(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL);s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const r=s.getParameter(s.UNPACK_ALIGNMENT);s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment);const l=s.getParameter(s.UNPACK_COLORSPACE_CONVERSION_WEBGL);s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const o=An(s,this.minFilter);s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,o),o!==s.NEAREST_MIPMAP_NEAREST&&o!==s.LINEAR_MIPMAP_NEAREST&&o!==s.NEAREST_MIPMAP_LINEAR&&o!==s.LINEAR_MIPMAP_LINEAR||(n=!0);const c=An(s,this.magFilter);c&&s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,c);const u=An(s,this.wrapS);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,u);const h=An(s,this.wrapT);h&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,h);const p=An(s,this.format,this.encoding),A=An(s,this.type),d=In(s,this.internalFormat,p,A,this.encoding,!1);if(this.target===s.TEXTURE_CUBE_MAP){if(m.isArray(e)){const t=e,n=[s.TEXTURE_CUBE_MAP_POSITIVE_X,s.TEXTURE_CUBE_MAP_NEGATIVE_X,s.TEXTURE_CUBE_MAP_POSITIVE_Y,s.TEXTURE_CUBE_MAP_NEGATIVE_Y,s.TEXTURE_CUBE_MAP_POSITIVE_Z,s.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,i=n.length;e<i;e++)s.texImage2D(n[e],0,d,p,A,t[e])}}else s.texImage2D(s.TEXTURE_2D,0,d,p,A,e);n&&s.generateMipmap(this.target),s.bindTexture(this.target,null),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,i),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a),s.pixelStorei(s.UNPACK_ALIGNMENT,r),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l)}setCompressedData({mipmaps:e,props:t={}}){const s=this.gl,n=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),s.activeTexture(s.TEXTURE0+0),s.bindTexture(this.target,this.texture);let i=e.length>1;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,this.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,s.NONE);const a=An(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);const r=An(s,this.wrapT);if(r&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,r),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){const e=An(s,this.wrapR);e&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,e),s.texParameteri(this.type,s.TEXTURE_WRAP_R,e)}i?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,yn(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,yn(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,An(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,An(s,this.magFilter)));const l=An(s,this.format,this.encoding),o=An(s,this.type),c=In(s,this.internalFormat,l,o,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,c,e[0].width,e[0].height);for(let t=0,n=e.length;t<n;t++){const n=e[t];1023!==this.format?null!==l?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,n.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):s.texSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,l,o,n.data)}s.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const s=An(t,e.minFilter);s&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,s),s!==t.NEAREST_MIPMAP_NEAREST&&s!==t.LINEAR_MIPMAP_NEAREST&&s!==t.NEAREST_MIPMAP_LINEAR&&s!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const s=An(t,e.magFilter);s&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,s))}if(void 0!==e.wrapS){const s=An(t,e.wrapS);s&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,s))}if(void 0!==e.wrapT){const s=An(t,e.wrapT);s&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,s))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function In(e,t,s,n,i,a=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let r=s;return s===e.RED&&(n===e.FLOAT&&(r=e.R32F),n===e.HALF_FLOAT&&(r=e.R16F),n===e.UNSIGNED_BYTE&&(r=e.R8)),s===e.RG&&(n===e.FLOAT&&(r=e.RG32F),n===e.HALF_FLOAT&&(r=e.RG16F),n===e.UNSIGNED_BYTE&&(r=e.RG8)),s===e.RGBA&&(n===e.FLOAT&&(r=e.RGBA32F),n===e.HALF_FLOAT&&(r=e.RGBA16F),n===e.UNSIGNED_BYTE&&(r=3001===i&&!1===a?e.SRGB8_ALPHA8:e.RGBA8),n===e.UNSIGNED_SHORT_4_4_4_4&&(r=e.RGBA4),n===e.UNSIGNED_SHORT_5_5_5_1&&(r=e.RGB5_A1)),r!==e.R16F&&r!==e.R32F&&r!==e.RG16F&&r!==e.RG32F&&r!==e.RGBA16F&&r!==e.RGBA32F||Ke(e,"EXT_color_buffer_float"),r}function yn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function mn(e){if(!vn(e.width)||!vn(e.height)){const t=document.createElement("canvas");t.width=wn(e.width),t.height=wn(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function vn(e){return 0==(e&e-1)}function wn(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class gn extends _{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new Je({texture:new fn({gl:this.scene.canvas.gl}),matrix:h.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=h.vec2([0,0]),this._scale=h.vec2([1,1]),this._rotate=h.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new fn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,s;0===this._translate[0]&&0===this._translate[1]||(t=h.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(s=h.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?h.mulMat4(t,s):s),0!==this._rotate&&(s=h.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?h.mulMat4(t,s):s),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=mn(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let s=new Image;s.onload=function(){s=mn(s),t._state.texture.setImage(s,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},s.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}const En=d.memory,Tn=h.AABB3();class bn extends Et{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new Je({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=h.OBB3();const s=this._state,n=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":s.primitive=n.POINTS,s.primitiveName=t.primitive;break;case"lines":s.primitive=n.LINES,s.primitiveName=t.primitive;break;case"line-loop":s.primitive=n.LINE_LOOP,s.primitiveName=t.primitive;break;case"line-strip":s.primitive=n.LINE_STRIP,s.primitiveName=t.primitive;break;case"triangles":s.primitive=n.TRIANGLES,s.primitiveName=t.primitive;break;case"triangle-strip":s.primitive=n.TRIANGLE_STRIP,s.primitiveName=t.primitive;break;case"triangle-fan":s.primitive=n.TRIANGLE_FAN,s.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),s.primitive=n.TRIANGLES,s.primitiveName=t.primitive}if(t.positions)if(t.indices){var i;if(t.positionsDecodeMatrix);else{const e=Bt.getPositionsBounds(t.positions),a=Bt.compressPositions(t.positions,e.min,e.max);i=a.quantized,s.positionsDecodeMatrix=a.decodeMatrix,s.positionsBuf=new Oe(n,n.ARRAY_BUFFER,i,i.length,3,n.STATIC_DRAW),En.positions+=s.positionsBuf.numItems,h.positions3ToAABB3(t.positions,this._aabb),h.positions3ToAABB3(i,Tn,s.positionsDecodeMatrix),h.AABB3ToOBB3(Tn,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);s.colorsBuf=new Oe(n,n.ARRAY_BUFFER,e,e.length,4,n.STATIC_DRAW),En.colors+=s.colorsBuf.numItems}if(t.uv){const e=Bt.getUVBounds(t.uv),i=Bt.compressUVs(t.uv,e.min,e.max),a=i.quantized;s.uvDecodeMatrix=i.decodeMatrix,s.uvBuf=new Oe(n,n.ARRAY_BUFFER,a,a.length,2,n.STATIC_DRAW),En.uvs+=s.uvBuf.numItems}if(t.normals){const e=Bt.compressNormals(t.normals);let i=s.compressGeometry;s.normalsBuf=new Oe(n,n.ARRAY_BUFFER,e,e.length,3,n.STATIC_DRAW,i),En.normals+=s.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);s.indicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,e,e.length,1,n.STATIC_DRAW),En.indices+=s.indicesBuf.numItems;const a=Tt(i,e,s.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,a,a.length,1,n.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),En.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),En.meshes--}}var Dn={};function Pn(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let s=e.divisions||1;s<0&&(console.error("negative divisions not allowed - will invert"),s*=-1),s<1&&(s=1),t=t||10,s=s||10;const n=t/s,i=t/2,a=[],r=[];let l=0;for(let e=0,t=-i;e<=s;e++,t+=n)a.push(-i),a.push(0),a.push(t),a.push(i),a.push(0),a.push(t),a.push(t),a.push(0),a.push(-i),a.push(t),a.push(0),a.push(i),r.push(l++),r.push(l++),r.push(l++),r.push(l++);return m.apply(e,{primitive:"lines",positions:a,indices:r})}function Rn(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);let n=e.xSegments||1;n<0&&(console.error("negative xSegments not allowed - will invert"),n*=-1),n<1&&(n=1);let i=e.xSegments||1;i<0&&(console.error("negative zSegments not allowed - will invert"),i*=-1),i<1&&(i=1);const a=e.center,r=a?a[0]:0,l=a?a[1]:0,o=a?a[2]:0,c=t/2,u=s/2,h=Math.floor(n)||1,p=Math.floor(i)||1,A=h+1,d=p+1,f=t/h,I=s/p,y=new Float32Array(A*d*3),v=new Float32Array(A*d*3),w=new Float32Array(A*d*2);let g,E,T,b,D,P,R,C=0,_=0;for(g=0;g<d;g++){const e=g*I-u;for(E=0;E<A;E++)T=E*f-c,y[C]=T+r,y[C+1]=l,y[C+2]=-e+o,v[C+2]=-1,w[_]=E/h,w[_+1]=(p-g)/p,C+=3,_+=2}C=0;const B=new(y.length/3>65535?Uint32Array:Uint16Array)(h*p*6);for(g=0;g<p;g++)for(E=0;E<h;E++)b=E+A*g,D=E+A*(g+1),P=E+1+A*(g+1),R=E+1+A*g,B[C]=R,B[C+1]=D,B[C+2]=b,B[C+3]=R,B[C+4]=P,B[C+5]=D,C+=6;return m.apply(e,{positions:y,normals:v,uv:w,indices:B})}function Cn(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let s=e.tube||.3;s<0&&(console.error("negative tube not allowed - will invert"),s*=-1);let n=e.radialSegments||32;n<0&&(console.error("negative radialSegments not allowed - will invert"),n*=-1),n<4&&(n=4);let i=e.tubeSegments||24;i<0&&(console.error("negative tubeSegments not allowed - will invert"),i*=-1),i<4&&(i=4);let a=e.arc||2*Math.PI;a<0&&(console.warn("negative arc not allowed - will invert"),a*=-1),a>360&&(a=360);const r=e.center;let l=r?r[0]:0,o=r?r[1]:0;const c=r?r[2]:0,u=[],p=[],A=[],d=[];let f,I,y,v,w,g,E,T,b,D,P,R;for(T=0;T<=i;T++)for(E=0;E<=n;E++)f=E/n*a,I=.785398+T/i*Math.PI*2,l=t*Math.cos(f),o=t*Math.sin(f),y=(t+s*Math.cos(I))*Math.cos(f),v=(t+s*Math.cos(I))*Math.sin(f),w=s*Math.sin(I),u.push(y+l),u.push(v+o),u.push(w+c),A.push(1-E/n),A.push(T/i),g=h.normalizeVec3(h.subVec3([y,v,w],[l,o,c],[]),[]),p.push(g[0]),p.push(g[1]),p.push(g[2]);for(T=1;T<=i;T++)for(E=1;E<=n;E++)b=(n+1)*T+E-1,D=(n+1)*(T-1)+E-1,P=(n+1)*(T-1)+E,R=(n+1)*T+E,d.push(b),d.push(D),d.push(P),d.push(P),d.push(R),d.push(b);return m.apply(e,{positions:u,normals:p,uv:A,indices:d})}Dn.load=function(e,t){var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=function(e){t(e.target.response)},s.send()},Dn.save=function(e,t){var s="data:application/octet-stream;base64,"+btoa(Dn.parse._buffToStr(e));window.location.href=s},Dn.clone=function(e){return JSON.parse(JSON.stringify(e))},Dn.bin={},Dn.bin.f=new Float32Array(1),Dn.bin.fb=new Uint8Array(Dn.bin.f.buffer),Dn.bin.rf=function(e,t){for(var s=Dn.bin.f,n=Dn.bin.fb,i=0;i<4;i++)n[i]=e[t+i];return s[0]},Dn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Dn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Dn.bin.rASCII0=function(e,t){for(var s="";0!=e[t];)s+=String.fromCharCode(e[t++]);return s},Dn.bin.wf=function(e,t,s){new Float32Array(e.buffer,t,1)[0]=s},Dn.bin.wsl=function(e,t,s){e[t]=s,e[t+1]=s>>8},Dn.bin.wil=function(e,t,s){e[t]=s,e[t+1]=s>>8,e[t+2]=s>>16,e[t+3]},Dn.parse={},Dn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),s="",n=0;n<t.length;n++)s=s.concat(String.fromCharCode(t[n]));return s},Dn.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),s=new Uint8Array(t),n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return t},Dn.parse._readLine=function(e,t){for(var s="";10!=e[t];)s+=String.fromCharCode(e[t++]);return s},Dn.parse.fromJSON=function(e){return JSON.parse(Dn.parse._buffToStr(e))},Dn.parse.toJSON=function(e){var t=JSON.stringify(e);return Dn.parse._strToBuff(t)},Dn.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},s={from:0,to:0},n=0,i=new Uint8Array(e);n<i.length;){var a=Dn.parse._readLine(i,n);n+=a.length+1;var r=(a=(a=a.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==r[0]&&(s.to=t.i_verts.length,null==t.groups[r[1]]&&(t.groups[r[1]]={from:t.i_verts.length,to:0}),s=t.groups[r[1]]),"v"==r[0]){var l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_verts.push(l,o,c)}if("vt"==r[0]){l=parseFloat(r[1]),o=1-parseFloat(r[2]);t.c_uvt.push(l,o)}if("vn"==r[0]){l=parseFloat(r[1]),o=parseFloat(r[2]),c=parseFloat(r[3]);t.c_norms.push(l,o,c)}if("f"==r[0]){var u=r[1].split("/"),h=r[2].split("/"),p=r[3].split("/"),A=parseInt(u[0])-1,d=parseInt(h[0])-1,f=parseInt(p[0])-1,I=parseInt(u[1])-1,y=parseInt(h[1])-1,m=parseInt(p[1])-1,v=parseInt(u[2])-1,w=parseInt(h[2])-1,g=parseInt(p[2])-1,E=t.c_verts.length/3,T=t.c_uvt.length/2,b=t.c_norms.length/3;if(A<0&&(A=E+A+1),d<0&&(d=E+d+1),f<0&&(f=E+f+1),I<0&&(I=T+I+1),y<0&&(y=T+y+1),m<0&&(m=T+m+1),v<0&&(v=b+v+1),w<0&&(w=b+w+1),g<0&&(g=b+g+1),t.i_verts.push(A,d,f),t.i_uvt.push(I,y,m),t.i_norms.push(v,w,g),5==r.length){var D=r[4].split("/"),P=parseInt(D[0])-1,R=parseInt(D[1])-1,C=parseInt(D[2])-1;P<0&&(P=E+P+1),R<0&&(R=T+R+1),C<0&&(C=b+C+1),t.i_verts.push(A,f,P),t.i_uvt.push(I,m,R),t.i_norms.push(v,g,C)}}}return s.to=t.i_verts.length,t},Dn.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},s={};s.ident=Dn.bin.ril(e,0),s.version=Dn.bin.ril(e,4),s.skinwidth=Dn.bin.ril(e,8),s.skinheight=Dn.bin.ril(e,12),s.framesize=Dn.bin.ril(e,16),s.num_skins=Dn.bin.ril(e,20),s.num_vertices=Dn.bin.ril(e,24),s.num_st=Dn.bin.ril(e,28),s.num_tris=Dn.bin.ril(e,32),s.num_glcmds=Dn.bin.ril(e,36),s.num_frames=Dn.bin.ril(e,40),s.offset_skins=Dn.bin.ril(e,44),s.offset_st=Dn.bin.ril(e,48),s.offset_tris=Dn.bin.ril(e,52),s.offset_frames=Dn.bin.ril(e,56),s.offset_glcmds=Dn.bin.ril(e,60),s.offset_end=Dn.bin.ril(e,64);var n=s.offset_st;t.c_uvt=[];for(var i=0;i<s.num_st;i++){var a=Dn.bin.rsl(e,n)/s.skinwidth,r=Dn.bin.rsl(e,n+2)/s.skinheight;t.c_uvt.push(a,r),n+=4}n=s.offset_tris;var l=[],o=[];t.i_verts=l,t.i_uvt=o;for(i=0;i<s.num_tris;i++)l.push(Dn.bin.rsl(e,n),Dn.bin.rsl(e,n+2),Dn.bin.rsl(e,n+4)),o.push(Dn.bin.rsl(e,n+6),Dn.bin.rsl(e,n+8),Dn.bin.rsl(e,n+10)),n+=12;n=s.offset_skins;t.skins=[];for(i=0;i<s.num_skins;i++)t.skins.push(Dn.bin.rASCII0(e,n)),n+=64;n=s.offset_frames;t.frames=[];var c=Dn.parse.fromMD2._normals;for(i=0;i<s.num_frames;i++){var u={},h=Dn.bin.rf(e,n),p=Dn.bin.rf(e,n+4),A=Dn.bin.rf(e,n+8);n+=12;var d=Dn.bin.rf(e,n),f=Dn.bin.rf(e,n+4),I=Dn.bin.rf(e,n+8);n+=12,u.name=Dn.bin.rASCII0(e,n),n+=16,u.verts=[],u.norms=[];for(var y=0;y<s.num_vertices;y++)u.verts.push(e[n]*h+d,e[n+1]*p+f,e[n+2]*A+I),u.norms.push(c[3*e[n+3]],c[3*e[n+3]+1],c[3*e[n+3]+2]),n+=4;t.frames.push(u)}return t},Dn.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Dn.parse.fromCollada=function(e){var t=Dn.parse._buffToStr(e),s=(new DOMParser).parseFromString(t,"text/xml"),n={},i=(s=s.childNodes[0]).getElementsByTagName("asset")[0],a=s.getElementsByTagName("library_geometries")[0],r=s.getElementsByTagName("library_images")[0],l=s.getElementsByTagName("library_materials")[0],o=s.getElementsByTagName("library_effects")[0];return i&&(n.asset=Dn.parse.fromCollada._asset(i)),a&&(n.geometries=Dn.parse.fromCollada._libGeometries(a)),r&&(n.images=Dn.parse.fromCollada._libImages(r)),l&&(n.materials=Dn.parse.fromCollada._libMaterials(l)),o&&(n.effects=Dn.parse.fromCollada._libEffects(o)),n},Dn.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Dn.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],s=0;s<e.length;s++){var n=e[s],i=Dn.parse.fromCollada._getMesh(n.getElementsByTagName("mesh")[0]);t.push(i)}return t},Dn.parse.fromCollada._getMesh=function(e){for(var t={},s=e.getElementsByTagName("source"),n=t.sources={},i=0;i<s.length;i++){for(var a=s[i].getElementsByTagName("float_array")[0].textContent.split(" "),r=a.length-(""==a[a.length-1]?1:0),l=new Array(r),o=0;o<r;o++)l[o]=parseFloat(a[o]);n[s[i].getAttribute("id")]=l}t.triangles=[];var c=e.getElementsByTagName("triangles");if(null==c)return t;for(i=0;i<c.length;i++){var u={},h=c[i];u.material=h.getAttribute("material");var p=h.getElementsByTagName("input"),A=[];for(o=0;o<p.length;o++){var d=p[o];l=[];A[parseInt(d.getAttribute("offset"))]=l;var f=d.getAttribute("semantic");u["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):d.getAttribute("source").substring(1),u["i_"+f]=l,n[u["s_"+f]]}var I=h.getElementsByTagName("p")[0].textContent.split(" "),y=3*Math.floor(I.length/3);for(o=0;o<y;o++)A[o%p.length].push(parseInt(I[o]));t.triangles.push(u)}return t},Dn.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("id")]=e[s].getElementsByTagName("init_from")[0].textContent;return t},Dn.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},s=0;s<e.length;s++)t[e[s].getAttribute("name")]=e[s].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Dn.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},s=0;s<e.length;s++){for(var n={},i=e[s].getElementsByTagName("newparam"),a=0;a<i.length;a++){var r=i[a].getElementsByTagName("surface")[0];r&&(n.surface=r.getElementsByTagName("init_from")[0].textContent)}t[e[s].getAttribute("id")]=n}return t},Dn.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Dn.bin.rsl(e,0))return null;for(var s=Dn.bin.ril(e,2),n=6;n<s;){var i=Dn.bin.rsl(e,n),a=Dn.bin.ril(e,n+2);15677==i&&(t.edit=Dn.parse.from3DS._edit3ds(e,n,a)),45056==i&&(t.keyf=Dn.parse.from3DS._keyf3ds(e,n,a)),n+=a}return t},Dn.parse.from3DS._edit3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);16384==a&&(null==n.objects&&(n.objects=[]),n.objects.push(Dn.parse.from3DS._edit_object(e,i,r))),i+=r}return n},Dn.parse.from3DS._keyf3ds=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);45058==a&&(null==n.desc&&(n.desc=[]),n.desc.push(Dn.parse.from3DS._keyf_objdes(e,i,r))),i+=r}return n},Dn.parse.from3DS._keyf_objdes=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);45072==a&&(n.hierarchy=Dn.parse.from3DS._keyf_objhierarch(e,i,r)),45073==a&&(n.dummy_name=Dn.bin.rASCII0(e,i+6)),i+=r}return n},Dn.parse.from3DS._keyf_objhierarch=function(e,t,s){var n={},i=t+6;return n.name=Dn.bin.rASCII0(e,i),i+=n.name.length+1,n.hierarchy=Dn.bin.rsl(e,i+4),n},Dn.parse.from3DS._edit_object=function(e,t,s){var n={},i=t+6;for(n.name=Dn.bin.rASCII0(e,i),i+=n.name.length+1;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);16640==a&&(n.mesh=Dn.parse.from3DS._obj_trimesh(e,i,r)),i+=r}return n},Dn.parse.from3DS._obj_trimesh=function(e,t,s){for(var n={},i=t+6;i<t+s;){var a=Dn.bin.rsl(e,i),r=Dn.bin.ril(e,i+2);16656==a&&(n.vertices=Dn.parse.from3DS._tri_vertexl(e,i,r)),16672==a&&(n.indices=Dn.parse.from3DS._tri_facel1(e,i,r)),16704==a&&(n.uvt=Dn.parse.from3DS._tri_mappingcoors(e,i,r)),16736==a&&(n.local=Dn.parse.from3DS._tri_local(e,i,r)),i+=r}return n},Dn.parse.from3DS._tri_vertexl=function(e,t,s){var n=[],i=t+6,a=Dn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Dn.bin.rf(e,i)),n.push(Dn.bin.rf(e,i+4)),n.push(Dn.bin.rf(e,i+8)),i+=12;return n},Dn.parse.from3DS._tri_facel1=function(e,t,s){var n=[],i=t+6,a=Dn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Dn.bin.rsl(e,i)),n.push(Dn.bin.rsl(e,i+2)),n.push(Dn.bin.rsl(e,i+4)),i+=8;return n},Dn.parse.from3DS._tri_mappingcoors=function(e,t,s){var n=[],i=t+6,a=Dn.bin.rsl(e,i);i+=2;for(var r=0;r<a;r++)n.push(Dn.bin.rf(e,i)),n.push(1-Dn.bin.rf(e,i+4)),i+=8;return n},Dn.parse.from3DS._tri_local=function(e,t,s){var n={},i=t+6;return n.X=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n.Y=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n.Z=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n.C=[Dn.bin.rf(e,i),Dn.bin.rf(e,i+4),Dn.bin.rf(e,i+8)],i+=12,n},Dn.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},s={};return s.id=Dn.bin.ril(e,0),s.verS=Dn.bin.ril(e,4),s.texS=Dn.bin.ril(e,8),s.indS=Dn.bin.ril(e,12),s.verO=Dn.bin.ril(e,16),s.verL=Dn.bin.ril(e,20),s.texO=Dn.bin.ril(e,24),s.texL=Dn.bin.ril(e,28),s.indO=Dn.bin.ril(e,32),s.indL=Dn.bin.ril(e,36),0!=s.verO&&(t.vertices=Dn.parse.fromBIV._readFloats(e,s.verO,s.verL)),0!=s.texO&&(t.uvt=Dn.parse.fromBIV._readFloats(e,s.texO,s.texL)),0!=s.indO&&(t.indices=Dn.parse.fromBIV._readInts(e,s.indO,s.indL,s.indS)),t},Dn.parse.toBIV=function(e){for(var t=0,s=0;s<e.indices.length;s++)t=Math.max(t,e.indices[s]);var n=32;t<=65535&&(n=16);var i=40;e.vertices&&(i+=4*e.vertices.length),e.uvt&&(i+=4*e.uvt.length),e.indices&&(i+=e.indices.length*n/8);var a=new Uint8Array(i);Dn.bin.wil(a,0,1769365870),Dn.bin.wil(a,4,32),Dn.bin.wil(a,8,32),Dn.bin.wil(a,12,n);var r=40;return e.vertices&&(Dn.bin.wil(a,16,r),Dn.bin.wil(a,20,4*e.vertices.length),Dn.parse.fromBIV._writeFloats(a,r,e.vertices),r+=4*e.vertices.length),e.uvt&&(Dn.bin.wil(a,24,r),Dn.bin.wil(a,28,4*e.uvt.length),Dn.parse.fromBIV._writeFloats(a,r,e.uvt),r+=4*e.uvt.length),e.indices&&(Dn.bin.wil(a,32,r),Dn.bin.wil(a,36,4*e.indices.length),Dn.parse.fromBIV._writeInts(a,r,e.indices,n)),a.buffer},Dn.parse.fromBIV._readFloats=function(e,t,s){for(var n=[],i=0;i<s/4;i++)n.push(Dn.bin.rf(e,t+4*i));return n},Dn.parse.fromBIV._writeFloats=function(e,t,s){for(var n=0;n<s.length;n++)Dn.bin.wf(e,t+4*n,s[n])},Dn.parse.fromBIV._readInts=function(e,t,s,n){for(var i=[],a=0;a<s/4;a++)16==n&&i.push(Dn.bin.rsl(e,t+2*a)),32==n&&i.push(Dn.bin.ril(e,t+4*a));return i},Dn.parse.fromBIV._writeInts=function(e,t,s,n){for(var i=0;i<s.length;i++)16==n&&Dn.bin.wsl(e,t+2*i,s[i]),32==n&&Dn.bin.wil(e,t+4*i,s[i])},Dn.gen={},Dn.gen.Plane=function(e,t,s,n){s||(s=1),n||(n=1);for(var i={verts:[],inds:[],uvt:[]},a=e+1,r=t+1,l=0;l<r;l++)for(var o=0;o<a;o++){var c=o*(2/e)-1,u=l*(2/t)-1;i.verts.push(c,u,0),i.uvt.push(s*o/e,n*l/t),l<t&&o<e&&i.inds.push(l*a+o,l*a+o+1,(l+1)*a+o,l*a+o+1,(l+1)*a+o,(l+1)*a+o+1)}return i},Dn.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Dn.gen.Sphere=function(e,t){for(var s={verts:[],inds:[],uvt:[]},n=e+1,i=t+1,a=0;a<i;a++)for(var r=0;r<n;r++){var l=-Math.PI/2+a*Math.PI/t,o=2*r*Math.PI/e,c=Math.cos(l)*Math.cos(o),u=Math.sin(l),h=Math.cos(l)*Math.sin(o);s.verts.push(c,u,h),s.uvt.push(r/e,a/t),a<t&&r<e&&s.inds.push(n*a+r,n*a+r+1,n*(a+1)+r,n*a+r+1,n*(a+1)+r,n*(a+1)+r+1)}return s},Dn.mat={},Dn.mat.scale=function(e,t,s){return[e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1]},Dn.mat.translate=function(e,t,s){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1]},Dn.mat.rotateDeg=function(e,t,s){var n=Math.PI/180;return Dn.mat.rotate(e*n,t*n,s*n)},Dn.mat.rotate=function(e,t,s){var n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i=e,a=t,r=s,l=Math.cos(i),o=Math.cos(a),c=Math.cos(r),u=Math.sin(i),h=Math.sin(a),p=Math.sin(r);return n[0]=o*c,n[1]=-o*p,n[2]=h,n[4]=l*p+u*h*c,n[5]=l*c-u*h*p,n[6]=-u*o,n[8]=u*p-l*h*c,n[9]=u*c+l*h*p,n[10]=l*o,n},Dn.edit={},Dn.edit.interpolate=function(e,t,s,n){for(var i=0;i<e.length;i++)s[i]=e[i]+n*(t[i]-e[i])},Dn.edit.transform=function(e,t){for(var s=0;s<e.length;s+=3){var n=e[s],i=e[s+1],a=e[s+2];e[s+0]=t[0]*n+t[4]*i+t[8]*a+t[12],e[s+1]=t[1]*n+t[5]*i+t[9]*a+t[13],e[s+2]=t[2]*n+t[6]*i+t[10]*a+t[14]}},Dn.edit.unwrap=function(e,t,s){for(var n=new Array(Math.floor(e.length/3)*s),i=0;i<e.length;i++)for(var a=0;a<s;a++)n[i*s+a]=t[e[i]*s+a];return n},Dn.edit.remap=function(e,t,s,n){for(var i=new Array(s.length),a=0;a<e.length;a++)for(var r=0;r<n;r++)i[t[a]*n+r]=s[e[a]*n+r];return i},Dn.utils={},Dn.utils.getAABB=function(e){var t,s,n,i,a,r;i=a=r=-(t=s=n=999999999);for(var l=0;l<e.length;l+=3){var o=e[l+0],c=e[l+1],u=e[l+2];o<t&&(t=o),o>i&&(i=o),c<s&&(s=c),c>a&&(a=c),u<n&&(n=u),c>r&&(r=u)}return{min:{x:t,y:s,z:n},max:{x:i,y:a,z:r}}};class _n extends _{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=h.vec3(t.pos||[0,0,0]),this._up=h.vec3(t.up||[0,1,0]),this._normal=h.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=h.vec3(),this._rtcPos=h.vec3(),this._imageSize=h.vec2(),this._texture=new gn(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new an(this,{matrix:h.inverseMat4(h.lookAtMat4v(this._pos,h.subVec3(this._pos,this._normal,h.mat4()),this._up,h.mat4())),children:[this._bitmapMesh=new Vs(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new Nt(this,Rn({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ht(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height*e,1,this._height]}}class Bn extends _{constructor(e,t={}){super(e,t),this._positions=t.positions||[];const s=new Float32Array(this._positions.length),n=h.vec3(),i=V(this._positions,new Float32Array(this._positions.length),n,100);if(t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._mesh=new Vs(this,{visible:t.visible,clippable:t.clippable,collidable:t.collidable,geometry:new bn(this,{primitive:"lines",positions:i?s:this._positions,indices:this._indices,origin:i?n:null}),material:new Ht(this,{diffuse:t.color||[0,0,0],emissive:t.color||[0,0,0]})}),this.scene._lineSetCreated(this)}set visible(e){this._mesh.visible=e}get visible(){return this._mesh.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}const On=h.vec3(),Sn=h.vec3(),Nn=h.vec3(),xn=h.vec3();function Ln(e){return{x:e[0],y:e[1],z:e[2]}}function Mn(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Fn(e){return new Float64Array([e[0],-e[2],e[1]])}function Hn(e){return new Float64Array([e[0],e[2],-e[1]])}const Un=h.vec3(),Gn=(e,t,s,n)=>{var i=e-s,a=t-n;return Math.sqrt(i*i+a*a)};class jn extends _{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var s=this.plugin.viewer.scene;this._originMarker=new ie(s,t.origin),this._targetMarker=new ie(s,t.target),this._originWorld=h.vec3(),this._targetWorld=h.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const n=t.onMouseOver?e=>{t.onMouseOver(e,this)}:null,i=t.onMouseLeave?e=>{t.onMouseLeave(e,this)}:null,a=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,r=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._targetDot=new re(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthWire=new ae(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisWire=new ae(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisWire=new ae(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisWire=new ae(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._lengthLabel=new le(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._xAxisLabel=new le(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._yAxisLabel=new le(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._zAxisLabel=new le(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:n,onMouseLeave:i,onMouseWheel:r,onContextMenu:a}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=s.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=s.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=s.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=s.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=s.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=s.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=s.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(h.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(t>-.3||s>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){h.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var n=this._pp,i=this._cp,a=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var r=a.top-t.top,l=a.left-t.left,o=e.canvas.boundary,c=o[2],u=o[3],p=0;const s=this.plugin.viewer.scene.metrics,f=s.scale,I=s.units,y=s.unitsInfo[I].abbrev;for(var A=0,d=n.length;A<d;A+=4)i[p]=l+Math.floor((1+n[A+0]/n[A+3])*c/2),i[p+1]=r+Math.floor((1-n[A+1]/n[A+3])*u/2),p+=2;if(this._originDot.setPos(i[0],i[1]),this._targetDot.setPos(i[6],i[7]),this._lengthWire.setStartAndEnd(i[0],i[1],i[6],i[7]),this._xAxisWire.setStartAndEnd(i[0],i[1],i[2],i[3]),this._yAxisWire.setStartAndEnd(i[2],i[3],i[4],i[5]),this._zAxisWire.setStartAndEnd(i[4],i[5],i[6],i[7]),this.labelsVisible){this._lengthLabel.setPosOnWire(i[0],i[1],i[6],i[7]),this._xAxisLabel.setPosOnWire(i[0],i[1],i[2],i[3]),this._yAxisLabel.setPosOnWire(i[2],i[3],i[4],i[5]),this._zAxisLabel.setPosOnWire(i[4],i[5],i[6],i[7]);const e=this._approximate?" ~ ":" = ";this._length=Math.abs(h.lenVec3(h.subVec3(this._targetWorld,this._originWorld,Un))),this._lengthLabel.setText(e+(this._length*f).toFixed(2)+y);const t=Math.abs(Gn(i[0],i[1],i[2],i[3])),s=Math.abs(Gn(i[2],i[3],i[4],i[5])),n=Math.abs(Gn(i[4],i[5],i[6],i[7])),a=this.plugin.labelMinAxisLength;this._xAxisLabelCulled=t<a,this._yAxisLabelCulled=s<a,this._zAxisLabelCulled=n<a,this._xAxisLabelCulled?this._xAxisLabel.setCulled(!0):(this._xAxisLabel.setText(e+Math.abs((this._targetWorld[0]-this._originWorld[0])*f).toFixed(2)+y),this._xAxisLabel.setCulled(!this.axisVisible)),this._yAxisLabelCulled?this._yAxisLabel.setCulled(!0):(this._yAxisLabel.setText(e+Math.abs((this._targetWorld[1]-this._originWorld[1])*f).toFixed(2)+y),this._yAxisLabel.setCulled(!this.axisVisible)),this._zAxisLabelCulled?this._zAxisLabel.setCulled(!0):(this._zAxisLabel.setText(e+Math.abs((this._targetWorld[2]-this._originWorld[2])*f).toFixed(2)+y),this._zAxisLabel.setCulled(!this.axisVisible))}else this._lengthLabel.setCulled(!0),this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0);this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._xAxisWire.setVisible(this.axisVisible&&this.xAxisVisible),this._yAxisWire.setVisible(this.axisVisible&&this.yAxisVisible),this._zAxisWire.setVisible(this.axisVisible&&this.zAxisVisible),this._lengthWire.setVisible(this.wireVisible),this._lengthLabel.setCulled(!this.wireVisible),this._cpDirty=!1}}_isSliced(e){const t=this.scene._sectionPlanesState.sectionPlanes;for(let s=0,n=t.length;s<n;s++){const n=t[s];if(h.planeClipsPositions3(n.pos,n.dir,e,4))return!0}return!1}set approximate(e){e=!1!==e,this._approximate!==e&&(this._approximate=e,this._cpDirty=!0,this._needUpdate(0))}get approximate(){return this._approximate}get origin(){return this._originMarker}get target(){return this._targetMarker}get length(){this._update();const e=this.plugin.viewer.scene.metrics.scale;return this._length*e}get color(){return this._color}set color(e){this._color=e,this._originDot.setFillColor(e),this._targetDot.setFillColor(e),this._lengthWire.setColor(e),this._lengthLabel.setFillColor(e)}set visible(e){e=void 0!==e?Boolean(e):this.plugin.defaultVisible,this._visible=e,this._originDot.setVisible(this._visible&&this._originVisible),this._targetDot.setVisible(this._visible&&this._targetVisible),this._lengthWire.setVisible(this._visible&&this._wireVisible),this._lengthLabel.setVisible(this._visible&&this._wireVisible);const t=this._visible&&this._axisVisible&&this._xAxisVisible,s=this._visible&&this._axisVisible&&this._yAxisVisible,n=this._visible&&this._axisVisible&&this._zAxisVisible;this._xAxisWire.setVisible(t),this._yAxisWire.setVisible(s),this._zAxisWire.setVisible(n),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._yAxisLabel.setVisible(s&&!this._yAxisLabelCulled),this._zAxisLabel.setVisible(n&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get visible(){return this._visible}set originVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultOriginVisible,this._originVisible=e,this._originDot.setVisible(this._visible&&this._originVisible)}get originVisible(){return this._originVisible}set targetVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultTargetVisible,this._targetVisible=e,this._targetDot.setVisible(this._visible&&this._targetVisible)}get targetVisible(){return this._targetVisible}set axisEnabled(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisEnabled=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._xAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._xAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisEnabled(){return this._axisEnabled}set axisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._axisVisible=e;var t=this._visible&&this._axisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t&&this._xAxisVisible),this._yAxisWire.setVisible(t&&this._yAxisVisible),this._zAxisWire.setVisible(t&&this._zAxisVisible),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._xAxisVisible),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._yAxisVisible),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._zAxisVisible),this._cpDirty=!0,this._needUpdate()}get axisVisible(){return this._axisVisible}set xAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._xAxisVisible=e;const t=this._visible&&this._axisVisible&&this._xAxisVisible&&this._axisEnabled;this._xAxisWire.setVisible(t),this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get xAxisVisible(){return this._xAxisVisible}set yAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._yAxisVisible=e;const t=this._visible&&this._axisVisible&&this._yAxisVisible&&this._axisEnabled;this._yAxisWire.setVisible(t),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get yAxisVisible(){return this._yAxisVisible}set zAxisVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultAxisVisible,this._zAxisVisible=e;const t=this._visible&&this._axisVisible&&this._zAxisVisible&&this._axisEnabled;this._zAxisWire.setVisible(t),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled),this._cpDirty=!0,this._needUpdate()}get zAxisVisible(){return this._zAxisVisible}set wireVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultWireVisible,this._wireVisible=e;var t=this._visible&&this._wireVisible;this._lengthLabel.setVisible(t),this._lengthWire.setVisible(t)}get wireVisible(){return this._wireVisible}set labelsVisible(e){e=void 0!==e?Boolean(e):this.plugin.defaultLabelsVisible,this._labelsVisible=e;var t=this._visible&&this._labelsVisible;this._xAxisLabel.setVisible(t&&!this._xAxisLabelCulled&&this._clickable&&this._axisEnabled),this._yAxisLabel.setVisible(t&&!this._yAxisLabelCulled&&this._clickable&&this._axisEnabled),this._zAxisLabel.setVisible(t&&!this._zAxisLabelCulled&&this._clickable&&this._axisEnabled),this._lengthLabel.setVisible(t),this._cpDirty=!0,this._needUpdate()}get labelsVisible(){return this._labelsVisible}setHighlighted(e){this._originDot.setHighlighted(e),this._targetDot.setHighlighted(e),this._xAxisWire.setHighlighted(e),this._yAxisWire.setHighlighted(e),this._zAxisWire.setHighlighted(e),this._xAxisLabel.setHighlighted(e),this._yAxisLabel.setHighlighted(e),this._zAxisLabel.setHighlighted(e),this._lengthWire.setHighlighted(e),this._lengthLabel.setHighlighted(e)}set clickable(e){e=!!e,this._clickable=e,this._originDot.setClickable(this._clickable),this._targetDot.setClickable(this._clickable),this._xAxisWire.setClickable(this._clickable),this._yAxisWire.setClickable(this._clickable),this._zAxisWire.setClickable(this._clickable),this._lengthWire.setClickable(this._clickable),this._xAxisLabel.setClickable(this._clickable),this._yAxisLabel.setClickable(this._clickable),this._zAxisLabel.setClickable(this._clickable),this._lengthLabel.setClickable(this._clickable)}get clickable(){return this._clickable}destroy(){const e=this.plugin.viewer.scene,t=e.metrics;this._onViewMatrix&&e.camera.off(this._onViewMatrix),this._onProjMatrix&&e.camera.off(this._onProjMatrix),this._onCanvasBoundary&&e.canvas.off(this._onCanvasBoundary),this._onMetricsUnits&&t.off(this._onMetricsUnits),this._onMetricsScale&&t.off(this._onMetricsScale),this._onMetricsOrigin&&t.off(this._onMetricsOrigin),this._onSectionPlaneUpdated&&e.off(this._onSectionPlaneUpdated),this._originDot.destroy(),this._targetDot.destroy(),this._xAxisWire.destroy(),this._yAxisWire.destroy(),this._zAxisWire.destroy(),this._lengthLabel.destroy(),this._xAxisLabel.destroy(),this._yAxisLabel.destroy(),this._zAxisLabel.destroy(),this._lengthWire.destroy(),super.destroy()}}class Vn extends _{get active(){}set snapping(e){}get snapping(){return!0}activate(){}deactivate(){}reset(){}destroy(){}}class kn extends Vn{constructor(e,t={}){super(e.viewer.scene),this.pointerLens=t.pointerLens,this._active=!1;const s=document.createElement("div"),n=this.scene.canvas.canvas;n.parentNode.insertBefore(s,n),s.style.background="black",s.style.border="2px solid blue",s.style.borderRadius="10px",s.style.width="5px",s.style.height="5px",s.style.margin="-200px -200px",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",this._markerDiv=s,this._currentDistanceMeasurement=null,this._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},this._onCameraControlHoverSnapOrSurface=null,this._onCameraControlHoverSnapOrSurfaceOff=null,this._onMouseDown=null,this._onMouseUp=null,this._onCanvasTouchStart=null,this._onCanvasTouchEnd=null,this._snapping=!1!==t.snapping,this._mouseState=0,this._attachPlugin(e,t)}_attachPlugin(e,t={}){this.distanceMeasurementsPlugin=e,this.plugin=e}get active(){return this._active}set snapping(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}get snapping(){return this._snapping}activate(){if(this._active)return;this.fire("activated",!0);const e=this.distanceMeasurementsPlugin,t=this.scene,s=e.viewer.cameraControl,n=t.canvas.canvas;t.input;let i=!1;const a=h.vec3(),r=h.vec2();let l,o;this._mouseState=0,this._onCameraControlHoverSnapOrSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;i=!0,a.set(e.worldPos),r.set(e.canvasPos),0===this._mouseState?(this._markerDiv.style.marginLeft=t[0]-5+"px",this._markerDiv.style.marginTop=t[1]-5+"px",this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red")):(this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px"),n.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=a.slice(),this._markerDiv.style.marginLeft="-10000px",this._markerDiv.style.marginTop="-10000px")})),n.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(l=e.clientX,o=e.clientY)}),n.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>l+20||t.clientX<l-20||t.clientY>o+20||t.clientY<o-20||(this._currentDistanceMeasurement?i?(this._currentDistanceMeasurement.clickable=!0,this.distanceMeasurementsPlugin.fire("measurementEnd",this._currentDistanceMeasurement),this._currentDistanceMeasurement=null):(this._currentDistanceMeasurement.destroy(),this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement=null):i&&(this._currentDistanceMeasurement=e.createMeasurement({id:h.createUUID(),origin:{worldPos:a.slice()},target:{worldPos:a.slice()},approximate:!0}),this._currentDistanceMeasurementInitState.axisVisible=this._currentDistanceMeasurement.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurementInitState.xAxisVisible=this._currentDistanceMeasurement.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurementInitState.yAxisVisible=this._currentDistanceMeasurement.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurementInitState.zAxisVisible=this._currentDistanceMeasurement.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurementInitState.wireVisible=this._currentDistanceMeasurement.wireVisible,this._currentDistanceMeasurementInitState.targetVisible=this._currentDistanceMeasurement.targetVisible,this._currentDistanceMeasurement.clickable=!1,this.fire("measurementStart",this._currentDistanceMeasurement))))}),this._onCameraControlHoverSnapOrSurfaceOff=s.on(this._snapping?"hoverSnapOrSurfaceOff":"hoverOff",(e=>{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),i=!1,this._markerDiv.style.marginLeft="-100px",this._markerDiv.style.marginTop="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),n.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null)}destroy(){this.deactivate(),super.destroy()}}class Qn{constructor(){}getMetaModel(e,t,s){m.loadJSON(e,(e=>{t(e)}),(function(e){s(e)}))}getGLTF(e,t,s){m.loadArraybuffer(e,(e=>{t(e)}),(function(e){s(e)}))}getGLB(e,t,s){m.loadArraybuffer(e,(e=>{t(e)}),(function(e){s(e)}))}getArrayBuffer(e,t,s,n){!function(e,t,s,n){var i=()=>{};s=s||i,n=n||i;const a=/^data:(.*?)(;base64)?,(.*)$/,r=t.match(a);if(r){const e=!!r[2];var l=r[3];l=window.decodeURIComponent(l),e&&(l=window.atob(l));try{const e=new ArrayBuffer(l.length),t=new Uint8Array(e);for(var o=0;o<l.length;o++)t[o]=l.charCodeAt(o);window.setTimeout((function(){s(e)}),0)}catch(e){window.setTimeout((function(){n(e)}),0)}}else{const i=function(e){var t=e.lastIndexOf("/");return 0!==t?e.substring(0,t+1):""}(e),a=i+t,r=new XMLHttpRequest;r.open("GET",a,!0),r.responseType="arraybuffer",r.onreadystatechange=function(){4===r.readyState&&(200===r.status?s(r.response):n("loadArrayBuffer error : "+r.response))},r.send(null)}}(e,t,(e=>{s(e)}),(function(e){n(e)}))}}class Wn{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const s=this._messages[this._locale];if(!s)return null;const n=zn(e,s);return n?t?Kn(n,t):n:null}translatePlurals(e,t,s){const n=this._messages[this._locale];if(!n)return null;let i=zn(e,n);return i=0===(t=parseInt(""+t,10))?i.zero:t>1?i.other:i.one,i?(i=Kn(i,[t]),s&&(i=Kn(i,s)),i):null}fire(e,t,s){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==s&&(this._events[e]=t||!0);const n=this._eventSubs[e];if(n)for(const e in n)if(n.hasOwnProperty(e)){n[e].callback(t)}}on(t,s){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let n=this._eventSubs[t];n||(n={},this._eventSubs[t]=n);const i=this._eventSubIDMap.addItem();n[i]={callback:s},this._eventSubEvents[i]=t;const a=this._events[t];return void 0!==a&&s(a),i}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const s=this._eventSubs[t];s&&delete s[e],this._eventSubIDMap.removeItem(e)}}}function zn(e,t){if(t[e])return t[e];const s=e.split(".");let n=t;for(let e=0,t=s.length;n&&e<t;e++){n=n[s[e]]}return n}function Kn(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,s){return"{{"===e?"{":"}}"===e?"}":t[s]}))}class Yn extends _{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var s=e-t,n=e+t;s<0&&(s=0),n>1&&(n=1);var i=this.getPoint(s),a=this.getPoint(n),r=h.subVec3(a,i,[]);return h.normalizeVec3(r,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,s=[];for(t=0;t<=e;t++)s.push(this.getPoint(t/e));return s}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,s,n=[],i=this.getPoint(0),a=0;for(n.push(0),s=1;s<=e;s++)t=this.getPoint(s/e),a+=h.lenVec3(h.subVec3(t,i,[])),n.push(a),i=t;return this.cacheArcLengths=n,n}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var s,n=this._getLengths(),i=0,a=n.length;s=t||e*n[a-1];for(var r,l=0,o=a-1;l<=o;)if((r=n[i=Math.floor(l+(o-l)/2)]-s)<0)l=i+1;else{if(!(r>0)){o=i;break}o=i-1}if(n[i=o]===s)return i/(a-1);var c=n[i];return(i+(s-c)/(n[i+1]-c))/(a-1)}}class Xn extends Yn{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var s=(t.length-1)*e,n=Math.floor(s),i=s-n,a=t[0===n?n:n-1],r=t[n],l=t[n>t.length-2?t.length-1:n+1],o=t[n>t.length-3?t.length-1:n+2],c=h.vec3();return c[0]=h.catmullRomInterpolate(a[0],r[0],l[0],o[0],i),c[1]=h.catmullRomInterpolate(a[1],r[1],l[1],o[1],i),c[2]=h.catmullRomInterpolate(a[2],r[2],l[2],o[2],i),c}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const qn=h.vec3();const Jn=h.vec3(),Zn=h.vec3(),$n=h.vec3(),ei=h.vec3(),ti=h.vec3();class si extends _{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=h.vec3(),this._eye1=h.vec3(),this._up1=h.vec3(),this._look2=h.vec3(),this._eye2=h.vec3(),this._up2=h.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,s){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=s;const n=this.scene.camera,i=!!e.projection&&e.projection!==n.projection;let a,r,l,o,c;if(this._eye1[0]=n.eye[0],this._eye1[1]=n.eye[1],this._eye1[2]=n.eye[2],this._look1[0]=n.look[0],this._look1[1]=n.look[1],this._look1[2]=n.look[2],this._up1[0]=n.up[0],this._up1[1]=n.up[1],this._up1[2]=n.up[2],this._orthoScale1=n.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)a=e.aabb;else if(6===e.length)a=e;else if(e.eye&&e.look||e.up)r=e.eye,l=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)l=e.look;else{let n=e;if((m.isNumeric(n)||m.isString(n))&&(c=n,n=this.scene.components[c],!n))return this.error("Component not found: "+m.inQuotes(c)),void(t&&(s?t.call(s):t()));i||(a=n.aabb||this.scene.aabb)}const u=e.poi;if(a){if(a[3]<a[0]||a[4]<a[1]||a[5]<a[2])return;if(a[3]===a[0]&&a[4]===a[1]&&a[5]===a[2])return;a=a.slice();const t=h.getAABB3Center(a);this._look2=u||t;const s=h.subVec3(this._eye1,this._look1,Jn),n=h.normalizeVec3(s),i=u?h.getAABB3DiagPoint(a,u):h.getAABB3Diag(a),r=e.fitFOV||this._fitFOV,l=Math.abs(i/Math.tan(r*h.DEGTORAD));this._orthoScale2=1.1*i,this._eye2[0]=this._look2[0]+n[0]*l,this._eye2[1]=this._look2[1]+n[1]*l,this._eye2[2]=this._look2[2]+n[2]*l,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(r||l||o)&&(this._flyingEyeLookUp=!!r&&!!l&&!!o,this._flyingEye=!!r&&!l,this._flyingLook=!!l&&!r,r&&(this._eye2[0]=r[0],this._eye2[1]=r[1],this._eye2[2]=r[2]),l&&(this._look2[0]=l[0],this._look2[1]=l[1],this._look2[2]=l[2]),o&&(this._up2[0]=o[0],this._up2[1]=o[1],this._up2[2]=o[2]));i?("ortho"===e.projection&&"ortho"!==n.projection&&(this._projection2="ortho",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.ortho.matrix.slice(),n.projection="customProjection"),"perspective"===e.projection&&"perspective"!==n.projection&&(this._projection2="perspective",this._projMatrix1=n.projMatrix.slice(),this._projMatrix2=n.perspective.matrix.slice(),n.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,R.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var s,n,i,a,r;if(e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye||e.look||e.up)i=e.eye,a=e.look,r=e.up;else{let t=e;if((m.isNumeric(t)||m.isString(t))&&(n=t,t=this.scene.components[n],!t))return void this.error("Component not found: "+m.inQuotes(n));s=t.aabb||this.scene.aabb}const l=e.poi;if(s){if(s[3]<=s[0]||s[4]<=s[1]||s[5]<=s[2])return;var o=l?h.getAABB3DiagPoint(s,l):h.getAABB3Diag(s);let n;a=l||h.getAABB3Center(s,a),this._trail?h.subVec3(t.look,a,ti):h.subVec3(t.eye,t.look,ti),h.normalizeVec3(ti);n=(void 0!==e.fit?e.fit:this._fit)?Math.abs(o/Math.tan((e.fitFOV||this._fitFOV)*h.DEGTORAD)):h.lenVec3(h.subVec3(t.eye,t.look,Jn)),h.mulVec3Scalar(ti,n),t.eye=h.addVec3(a,ti,Jn),t.look=a,this.scene.camera.ortho.scale=1.1*o}else(i||a||r)&&(i&&(t.eye=i),a&&(t.look=a),r&&(t.up=r));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const s=this.easing?si._ease(e,0,1,1):e,n=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(h.subVec3(n.eye,n.look,ti),n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,$n),n.look=h.subVec3($n,ti,Zn)):this._flyingLook&&(n.look=h.lerpVec3(s,0,1,this._look1,this._look2,Zn),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ei)):this._flyingEyeLookUp&&(n.eye=h.lerpVec3(s,0,1,this._eye1,this._eye2,$n),n.look=h.lerpVec3(s,0,1,this._look1,this._look2,Zn),n.up=h.lerpVec3(s,0,1,this._up1,this._up2,ei)),this._projection2){const t="ortho"===this._projection2?si._easeOutExpo(e,0,1,1):si._easeInCubic(e,0,1,1);n.customProjection.matrix=h.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else n.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return n.ortho.scale=this._orthoScale2,void this.stop();R.scheduleTask(this._update,this)}static _ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}static _easeInCubic(e,t,s,n){return s*(e/=n)*e*e+t}static _easeOutExpo(e,t,s,n){return s*(1-Math.pow(2,-10*e/n))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class ni extends _{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new si(this),this._t=0,this.state=ni.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,s;const n=performance.now(),i=this._lastTime?.001*(n-this._lastTime):0;if(this._lastTime=n,0!==i)switch(this.state){case ni.SCRUBBING:return;case ni.PLAYING:if(this._t+=this._playingRate*i,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=ni.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case ni.PLAYING_TO:s=this._t+this._playingRate*i*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=ni.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}_ease(e,t,s,n){return-s*(e/=n)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=ni.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=ni.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const s=t.frames[e];s?this.playToT(s.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const s=this._cameraPath;if(!s)return;const n=s.frames[e];n?(this.state=ni.SCRUBBING,this._cameraFlightAnimation.flyTo(n,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=ni.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=ni.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=ni.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}ni.STOPPED=0,ni.SCRUBBING=1,ni.PLAYING=2,ni.PLAYING_TO=3;const ii=h.vec3(),ai=h.vec3();h.vec3();const ri=h.vec3([0,-1,0]),li=h.vec4([0,0,0,1]);function oi(e){if(!ci(e.width)||!ci(e.height)){const t=document.createElement("canvas");t.width=ui(e.width),t.height=ui(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function ci(e){return 0==(e&e-1)}function ui(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class hi extends _{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const s=this.scene.canvas.gl;this._state=new Je({texture:new fn({gl:s,target:s.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),d.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,s=this.scene.canvas.gl;this._images=[];let n=!1,i=0;for(let a=0;a<e.length;a++){const r=new Image;r.onload=function(){let e=r;const l=a;return function(){if(!n&&(e=oi(e),t._images[l]=e,i++,6===i)){let e=t._state.texture;e||(e=new fn({gl:s,target:s.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),r.onerror=function(){n=!0},r.src=e[a]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),d.memory.textures--,this._state.destroy()}}class pi{constructor(e){this._eye=h.vec3(),this._look=h.vec3(),this._up=h.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,s=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:s.fov,fovAxis:s.fovAxis,near:s.near,far:s.far};break;case"ortho":this._projection={projection:"ortho",scale:s.scale,near:s.near,far:s.far};break;case"frustum":this._projection={projection:"frustum",left:s.left,right:s.right,top:s.top,bottom:s.bottom,near:s.near,far:s.far};break;case"custom":this._projection={projection:"custom",matrix:s.matrix.slice()}}}restoreCamera(e,t){const s=e.camera,n=this._projection;function i(){switch(n.type){case"perspective":s.perspective.fov=n.fov,s.perspective.fovAxis=n.fovAxis,s.perspective.near=n.near,s.perspective.far=n.far;break;case"ortho":s.ortho.scale=n.scale,s.ortho.near=n.near,s.ortho.far=n.far;break;case"frustum":s.frustum.left=n.left,s.frustum.right=n.right,s.frustum.top=n.top,s.frustum.bottom=n.bottom,s.frustum.near=n.near,s.frustum.far=n.far;break;case"custom":s.customProjection.matrix=n.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:n.scale,projection:n.projection},(()=>{i(),t()})):(s.eye=this._eye,s.look=this._look,s.up=this._up,i(),s.projection=n.projection)}}const Ai=h.vec3();const di=h.vec3();class fi{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?m.apply(t,{}):null;const s=e.objects,n=!t||t.visible,i=!t||t.edges,a=!t||t.xrayed,r=!t||t.highlighted,l=!t||t.selected,o=!t||t.clippable,c=!t||t.pickable,u=!t||t.colorize,h=!t||t.opacity;for(let e in s)if(s.hasOwnProperty(e)){const t=s[e],p=this.numObjects;if(n&&(this.objectsVisible[p]=t.visible),i&&(this.objectsEdges[p]=t.edges),a&&(this.objectsXrayed[p]=t.xrayed),r&&(this.objectsHighlighted[p]=t.highlighted),l&&(this.objectsSelected[p]=t.selected),o&&(this.objectsClippable[p]=t.clippable),c&&(this.objectsPickable[p]=t.pickable),u){const e=t.colorize;e?(this.objectsColorize[3*p+0]=e[0],this.objectsColorize[3*p+1]=e[1],this.objectsColorize[3*p+2]=e[2],this.objectsHasColorize[p]=!0):this.objectsHasColorize[p]=!1}h&&(this.objectsOpacity[p]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,s=!t||t.visible,n=!t||t.edges,i=!t||t.xrayed,a=!t||t.highlighted,r=!t||t.selected,l=!t||t.clippable,o=!t||t.pickable,c=!t||t.colorize,u=!t||t.opacity;var h=0;const p=e.objects;for(let e in p)if(p.hasOwnProperty(e)){const t=p[e];s&&(t.visible=this.objectsVisible[h]),n&&(t.edges=this.objectsEdges[h]),i&&(t.xrayed=this.objectsXrayed[h]),a&&(t.highlighted=this.objectsHighlighted[h]),r&&(t.selected=this.objectsSelected[h]),l&&(t.clippable=this.objectsClippable[h]),o&&(t.pickable=this.objectsPickable[h]),c&&(this.objectsHasColorize[h]?(di[0]=this.objectsColorize[3*h+0],di[1]=this.objectsColorize[3*h+1],di[2]=this.objectsColorize[3*h+2],t.colorize=di):t.colorize=null),u&&(t.opacity=this.objectsOpacity[h]),h++}}}const Ii=h.OBB3(),yi=h.OBB3();class mi{constructor(e,t,s,n,i,a,r=null,l=0){this.model=e,this.object=null,this.parent=null,this.transform=i,this.textureSet=a,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabb=null,this._abbDirty=!1,this.layer=r,this.portionId=l,this._color=new Uint8Array([s[0],s[1],s[2],n]),this._colorize=new Uint8Array([s[0],s[1],s[2],n]),this._colorizing=!1,this._transparent=n<255,this.numTriangles=0,this.origin=null,this.entity=null,i&&i._addMesh(this)}_sceneModelDirty(){this._aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const s=e<255,n=this._transparent!==s;this._color[3]=e,this._colorize[3]=e,this._transparent=s,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),n&&this.layer.setTransparent(this.portionId,t,s)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,s,n){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,s,n)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabb=e}get aabb(){return this._aabbDirty&&(this.obb&&(this.transform?(h.transformOBB3(this.transform.worldMatrix,this.obb,Ii),h.transformOBB3(this.model.worldMatrix,Ii,yi),h.OBB3ToAABB3(yi,this._aabb)):(h.transformOBB3(this.model.worldMatrix,this.obb,Ii),h.OBB3ToAABB3(Ii,this._aabb))),this._aabbDirty=!1),this._aabb}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const vi=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let wi=0;const gi={NOT_RENDERED:0,COLOR_OPAQUE:1,COLOR_TRANSPARENT:2,SILHOUETTE_HIGHLIGHTED:3,SILHOUETTE_SELECTED:4,SILHOUETTE_XRAYED:5,EDGES_COLOR_OPAQUE:6,EDGES_COLOR_TRANSPARENT:7,EDGES_HIGHLIGHTED:8,EDGES_SELECTED:9,EDGES_XRAYED:10,PICK:11},Ei=new Float32Array([1,1,1,1]),Ti=new Float32Array([0,0,0,1]),bi=h.vec4(),Di=h.vec3(),Pi=h.vec3(),Ri=h.mat4();class Ci{constructor(e,t=!1,{instancing:s=!1,edges:n=!1}={}){this._scene=e,this._withSAO=t,this._instancing=s,this._edges=n,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:s}=t.canvas,{model:n,layerIndex:i}=e,a=t._sectionPlanesState.sectionPlanes.length;if(a>0){const r=t._sectionPlanesState.sectionPlanes,l=i*a,o=n.renderFlags;for(let t=0;t<a;t++){const n=this._uSectionPlanes[t];if(n){const i=o.sectionPlanesActivePerLayer[l+t];if(s.uniform1i(n.active,i?1:0),i){const i=r[t],a=e._state.origin;if(a){const e=k(i.dist,i.dir,a,Di);s.uniform3fv(n.pos,e)}else s.uniform3fv(n.pos,i.pos);s.uniform3fv(n.dir,i.dir)}}}}}_allocate(){const e=this._scene,t=e.canvas.gl,s=e._lightsState;if(this._program=new Be(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uRenderPass=n.getLocation("renderPass"),this._uColor=n.getLocation("color"),this._uColor||(this._uColor=n.getLocation("silhouetteColor")),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uPickInvisible=n.getLocation("pickInvisible"),this._uGammaFactor=n.getLocation("gammaFactor"),t.uniformBlockBinding(n.handle,t.getUniformBlockIndex(n.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=n.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=n.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=n.getLocation("zFar")),this._uLightAmbient=n.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const i=s.lights;let a;for(let e=0,t=i.length;e<t;e++)switch(a=i[e],a.type){case"dir":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=n.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=n.getLocation("lightColor"+e),this._uLightPos[e]=n.getLocation("lightPos"+e),this._uLightDir[e]=n.getLocation("lightDir"+e),this._uLightAttenuation[e]=n.getLocation("lightAttenuation"+e)}s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),s.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+t),pos:n.getLocation("sectionPlanePos"+t),dir:n.getLocation("sectionPlaneDir"+t)});this._aPosition=n.getAttribute("position"),this._aOffset=n.getAttribute("offset"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aMetallicRoughness=n.getAttribute("metallicRoughness"),this._aFlags=n.getAttribute("flags"),this._aPickColor=n.getAttribute("pickColor"),this._uPickZNear=n.getLocation("pickZNear"),this._uPickZFar=n.getLocation("pickZFar"),this._uPickClipPos=n.getLocation("pickClipPos"),this._uDrawingBufferSize=n.getLocation("drawingBufferSize"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrix=n.getAttribute("modelMatrix"),this._aModelMatrixCol0=n.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=n.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=n.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=n.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=n.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=n.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=n.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=n.getLocation("intensityRange")),this._uPointSize=n.getLocation("pointSize"),this._uNearPlaneHeight=n.getLocation("nearPlaneHeight")}_bindProgram(e){const t=this._scene,s=t.canvas.gl,n=this._program,i=t._lightsState,a=i.lights;n.bind(),e.textureUnit=0,this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i.getAmbientColorAndIntensity()),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,t.gammaFactor);for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}}_makeVAO(e){const t=this._scene.canvas.gl,s=t.createVertexArray();return t.bindVertexArray(s),this._instancing&&(this._aModelMatrixCol0.bindArrayBuffer(e.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(e.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(e.modelMatrixCol2Buf),t.vertexAttribDivisor(this._aModelMatrixCol0.location,1),t.vertexAttribDivisor(this._aModelMatrixCol1.location,1),t.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0&&(this._aModelNormalMatrixCol0.bindArrayBuffer(e.modelNormalMatrixCol0Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol0.location,1)),this._aModelNormalMatrixCol1&&(this._aModelNormalMatrixCol1.bindArrayBuffer(e.modelNormalMatrixCol1Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol1.location,1)),this._aModelNormalMatrixCol2&&(this._aModelNormalMatrixCol2.bindArrayBuffer(e.modelNormalMatrixCol2Buf),t.vertexAttribDivisor(this._aModelNormalMatrixCol2.location,1))),this._aPosition.bindArrayBuffer(e.positionsBuf),this._aUV&&this._aUV.bindArrayBuffer(e.uvBuf),this._aNormal&&this._aNormal.bindArrayBuffer(e.normalsBuf),this._aMetallicRoughness&&(this._aMetallicRoughness.bindArrayBuffer(e.metallicRoughnessBuf),this._instancing&&t.vertexAttribDivisor(this._aMetallicRoughness.location,1)),this._aColor&&(this._aColor.bindArrayBuffer(e.colorsBuf),this._instancing&&e.colorsBuf&&t.vertexAttribDivisor(this._aColor.location,1)),this._aFlags&&(this._aFlags.bindArrayBuffer(e.flagsBuf),this._instancing&&t.vertexAttribDivisor(this._aFlags.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(e.offsetsBuf),this._instancing&&t.vertexAttribDivisor(this._aOffset.location,1)),this._aPickColor&&(this._aPickColor.bindArrayBuffer(e.pickColorsBuf),this._instancing&&t.vertexAttribDivisor(this._aPickColor.location,1)),this._instancing,this._edges?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),s}drawLayer(e,t,s,{colorUniform:n=!1,incrementDrawState:i=!1}={}){const a=ge.MAX_TEXTURE_IMAGE_UNITS,r=this._scene,l=r.canvas.gl,{_state:o,model:c}=t,{textureSet:u,origin:p,positionsDecodeMatrix:A}=o,d=r._lightsState,f=r.pointsMaterial,{camera:I}=c.scene,{viewNormalMatrix:y,project:m}=I,v=e.pickViewMatrix||I.viewMatrix,{position:w,rotationMatrix:g,rotationMatrixConjugate:E,worldNormalMatrix:T}=c;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?l.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(o));let b=0;const D=16;this._matricesUniformBlockBufferData.set(E,0);const P=0!==p[0]||0!==p[1]||0!==p[2],R=0!==w[0]||0!==w[1]||0!==w[2];if(P||R){const e=Di;if(P){const t=h.transformPoint3(g,p,Pi);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=w[0],e[1]+=w[1],e[2]+=w[2],this._matricesUniformBlockBufferData.set(G(v,e,Ri),b+=D)}else this._matricesUniformBlockBufferData.set(v,b+=D);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||m.matrix,b+=D),this._matricesUniformBlockBufferData.set(A,b+=D),this._matricesUniformBlockBufferData.set(T,b+=D),this._matricesUniformBlockBufferData.set(y,b+=D),l.bindBuffer(l.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),l.bufferData(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,l.DYNAMIC_DRAW),l.bindBufferBase(l.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),l.uniform1i(this._uRenderPass,s),this.setSectionPlanesStateUniforms(t),r.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&l.uniform1f(this._uZFar,r.camera.project.far)}if(this._uPickInvisible&&l.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&l.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&l.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&l.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),this._uUVDecodeMatrix&&l.uniformMatrix3fv(this._uUVDecodeMatrix,!1,o.uvDecodeMatrix),this._uIntensityRange&&f.filterIntensity&&l.uniform2f(this._uIntensityRange,f.minIntensity,f.maxIntensity),this._uPointSize&&l.uniform1f(this._uPointSize,f.pointSize),this._uNearPlaneHeight){const e="ortho"===r.camera.projection?1:l.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));l.uniform1f(this._uNearPlaneHeight,e)}if(u){const{colorTexture:t,metallicRoughnessTexture:s,emissiveTexture:n,normalsTexture:i,occlusionTexture:r}=u;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uMetallicRoughMap&&s&&(this._program.bindTexture(this._uMetallicRoughMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uEmissiveMap&&n&&(this._program.bindTexture(this._uEmissiveMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uNormalMap&&i&&(this._program.bindTexture(this._uNormalMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a),this._uAOMap&&r&&(this._program.bindTexture(this._uAOMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a)}if(d.reflectionMaps.length>0&&d.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,d.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),d.lightMaps.length>0&&d.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,d.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++),this._withSAO){const t=r.sao;if(t.possible){const s=l.drawingBufferWidth,n=l.drawingBufferHeight;bi[0]=s,bi[1]=n,bi[2]=t.blendCutoff,bi[3]=t.blendFactor,l.uniform4fv(this._uSAOParams,bi),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%a,e.bindTexture++}}if(n){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(s===gi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const s=r.xrayMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===gi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const s=r.highlightMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else if(s===gi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const s=r.selectedMaterial._state,n=s[e],i=s[t];l.uniform4f(this._uColor,n[0],n[1],n[2],i)}else l.uniform4fv(this._uColor,this._edges?Ti:Ei)}this._draw({state:o,frameCtx:e,incrementDrawState:i}),l.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}class _i extends Ci{constructor(e,t,{instancing:s=!1,edges:n=!1}={}){super(e,t,{instancing:s,edges:n})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;if(this._edges)t.drawElements(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0);else{const e=n.pickElementsCount||s.indicesBuf.numItems,a=n.pickElementsOffset?n.pickElementsOffset*s.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,s.indicesBuf.itemType,a),i&&n.drawElements++}}}class Bi extends _i{constructor(e,t){super(e,t,{instancing:!1,edges:!0})}}class Oi extends Ci{constructor(e,t,{edges:s=!1}={}){super(e,t,{instancing:!0,edges:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;this._edges?t.drawElementsInstanced(t.LINES,s.edgeIndicesBuf.numItems,s.edgeIndicesBuf.itemType,0,s.numInstances):(t.drawElementsInstanced(t.TRIANGLES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++)}}class Si extends Oi{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class Ni extends Ci{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArrays(t.POINTS,0,s.positionsBuf.numItems),i&&n.drawArrays++}}class xi extends Ci{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawArraysInstanced(t.POINTS,0,s.positionsBuf.numItems,s.numInstances),i&&n.drawArrays++}}class Li extends Ci{_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElements(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0),i&&n.drawElements++}}class Mi extends Ci{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:s,frameCtx:n,incrementDrawState:i}=e;t.drawElementsInstanced(t.LINES,s.indicesBuf.numItems,s.indicesBuf.itemType,0,s.numInstances),i&&n.drawElements++}}class Fi extends _i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i;const a=[];a.push("#version 300 es"),a.push("// Triangles batching draw vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++)i=s.lights[e],"ambient"!==i.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")));a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;");for(let e=0,t=s.lights.length;e<t;e++)if(i=s.lights[e],"ambient"!==i.type){if("dir"===i.type)"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return a.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),a.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;")),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class Hi extends _i{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._lightsState,s=e._sectionPlanesState,n=s.sectionPlanes.length>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),this._withSAO&&(i.push("uniform sampler2D uOcclusionTexture;"),i.push("uniform vec4 uSAOParams;"),i.push("const float packUpscale = 256. / 255.;"),i.push("const float unpackDownScale = 255. / 256.;"),i.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),i.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),i.push("float unpackRGBToFloat( const in vec4 v ) {"),i.push(" return dot( v, unPackFactors );"),i.push("}")),n){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("uniform bool sectionPlaneActive"+e+";"),i.push("uniform vec3 sectionPlanePos"+e+";"),i.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(i),i.push("uniform vec4 lightAmbient;");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];"ambient"!==s.type&&(i.push("uniform vec4 lightColor"+e+";"),"dir"===s.type&&i.push("uniform vec3 lightDir"+e+";"),"point"===s.type&&i.push("uniform vec3 lightPos"+e+";"),"spot"===s.type&&(i.push("uniform vec3 lightPos"+e+";"),i.push("uniform vec3 lightDir"+e+";")))}if(i.push("in vec4 vViewPosition;"),i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),n){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)i.push("if (sectionPlaneActive"+e+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}i.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),i.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),i.push("float lambertian = 1.0;"),i.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),i.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),i.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,s=t.lights.length;e<s;e++){const s=t.lights[e];if("ambient"!==s.type){if("dir"===s.type)"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===s.type)"view"===s.space?i.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):i.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==s.type)continue;"view"===s.space?i.push("viewLightDir = normalize(lightDir"+e+");"):i.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}i.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),i.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return i.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(i.push(" float viewportWidth = uSAOParams[0];"),i.push(" float viewportHeight = uSAOParams[1];"),i.push(" float blendCutoff = uSAOParams[2];"),i.push(" float blendFactor = uSAOParams[3];"),i.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),i.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),i.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):i.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("}"),i}}class Ui extends _i{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching silhouette fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = vColor;"),a.push("}"),a}}class Gi extends Bi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class ji extends Bi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry edges drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Vi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class ki extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),this._addRemapClipPosLines(s),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Qi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec3 worldNormal = octDecode(normal.xy); "),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class Wi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push(" if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class zi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching depth fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("const float packUpScale = 256. / 255.;"),n.push("const float unpackDownscale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),n.push("const float shiftRight8 = 1.0 / 256.;"),n.push("vec4 packDepthToRGBA( const in float v ) {"),n.push(" vec4 r = vec4( fract( v * packFactors ), v );"),n.push(" r.yzw -= r.xyz * shiftRight8;"),n.push(" return r * packUpScale;"),n.push("}"),n.push("in vec2 vHighPrecisionZW;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}class Ki extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Yi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Batched geometry shadow vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" int colorFlag = int(flags) & 0xF;"),s.push(" bool visible = (colorFlag > 0);"),s.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push(" if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry shadow fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 encodeFloat( const in float v ) {"),s.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),s.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),s.push(" vec4 comp = fract(v * bitShift);"),s.push(" comp -= comp.xxyz * bitMask;"),s.push(" return comp;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" outColor = encodeFloat( gl_FragCoord.z); "),s.push("}"),s}}class Xi extends _i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Triangles batching quality draw vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("precision highp usampler2D;"),a.push("precision highp isampler2D;"),a.push("precision highp sampler2D;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("precision mediump usampler2D;"),a.push("precision mediump isampler2D;"),a.push("precision mediump sampler2D;"),a.push("#endif"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),a.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),a.push("vFragDepth = 1.0 + clipPos.w;")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Triangles batching quality draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),r.push("uniform sampler2D uAOMap;"),r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" 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.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),r.push(" return surf_norm;"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("float aoFactor = texture(uAOMap, vUV).r;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class qi extends _i{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching pick flat normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching pick flat normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class Ji extends _i{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles batching color texture vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._lightsState,n=e._sectionPlanesState,i=n.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Triangles batching color texture fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" 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.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),i){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}this._addMatricesUniformBlockLines(a),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("in vec4 vViewPosition;"),a.push("in vec4 vColor;"),a.push("in vec2 vUV;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=n.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { "),a.push(" discard;"),a.push(" }"),a.push("}")}a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("viewLightDir = normalize(lightDir"+e+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return a.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?a.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):a.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),a.push("float opacity = color.a;"),this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);")):a.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&a.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class Zi{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ui(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Vi(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ki(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Fi(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Fi(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Hi(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Hi(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ji(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ji(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Xi(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Xi(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ui(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new zi(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ki(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Gi(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ji(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Vi(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Qi(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new qi(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ki(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Wi(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Yi(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const $i={};class ea{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const ta=h.mat4(),sa=h.mat4();function na(e,t,s){const n=e.length,i=new Uint16Array(n),a=t[0],r=t[1],l=t[2],o=t[3]-a,c=t[4]-r,u=t[5]-l,p=65525,A=p/o,d=p/c,f=p/u,I=e=>e>=0?e:0;for(let t=0;t<n;t+=3)i[t+0]=Math.floor(I(e[t+0]-a)*A),i[t+1]=Math.floor(I(e[t+1]-r)*d),i[t+2]=Math.floor(I(e[t+2]-l)*f);return h.identityMat4(ta),h.translationMat4v(t,ta),h.identityMat4(sa),h.scalingMat4v([o/p,c/p,u/p],sa),h.mulMat4(ta,sa,s),i}function ia(e,t){const s=e[0],n=e[1],i=e[2],a=e[3]-s,r=e[4]-n,l=e[5]-i,o=65525;return h.identityMat4(ta),h.translationMat4v(e,ta),h.identityMat4(sa),h.scalingMat4v([a/o,r/o,l/o],sa),h.mulMat4(ta,sa,t),t}function aa(e,t,s){let n=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),i=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=n,t=i;e=(1-Math.abs(i))*(n>=0?1:-1),t=(1-Math.abs(n))*(i>=0?1:-1),n=e,i=t}return new Int8Array([Math[t](127.5*n+(n<0?-1:0)),Math[s](127.5*i+(i<0?-1:0))])}function ra(e){let t=e[0],s=e[1];t/=t<0?127:128,s/=s<0?127:128;const n=1-Math.abs(t)-Math.abs(s);n<0&&(t=(1-Math.abs(s))*(t>=0?1:-1),s=(1-Math.abs(t))*(s>=0?1:-1));const i=Math.sqrt(t*t+s*s+n*n);return[t/i,s/i,n/i]}const la=h.vec3(),oa=h.vec3(),ca=h.vec3(),ua=h.vec3(),ha=h.mat4();class pa extends Ci{drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||a.viewMatrix;this._vaoCache.has(t)?r.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=la;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=oa;if(o){const e=ca;h.transformPoint3(u,o,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,ha),y=ua,y[0]=a.eye[0]-t[0],y[1]=a.eye[1]-t[1],y[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,y),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,f),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(a.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),r.bindBuffer(r.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),r.bufferData(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,r.DYNAMIC_DRAW),r.bindBufferBase(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),l.indicesBuf.bind(),r.drawElements(r.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0),l.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("out float isPerspective;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("layout(location = 0) out highp ivec4 outCoords;"),s.push("layout(location = 1) out highp ivec4 outNormal;"),s.push("layout(location = 2) out lowp uvec4 outPickColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Aa=h.vec3(),da=h.vec3(),fa=h.vec3(),Ia=h.vec3(),ya=h.mat4();class ma extends Ci{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||a.viewMatrix;this._vaoCache.has(t)?r.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=Aa;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=da;if(o){const e=fa;h.transformPoint3(u,o,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,ya),y=Ia,y[0]=a.eye[0]-t[0],y[1]=a.eye[1]-t[1],y[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,y),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,f),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(a.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),r.bindBuffer(r.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),r.bufferData(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,r.DYNAMIC_DRAW),r.bindBufferBase(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElements(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0),l.edgeIndicesBuf.unbind()):r.drawArrays(r.POINTS,0,l.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0;e.pointsMaterial._state;const s=[];return s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapBatchingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("out highp ivec4 outCoords;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n<e.sectionPlanes.length;n++)s.push(" if (sectionPlaneActive"+n+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+n+".xyz, vWorldPosition.xyz - sectionPlanePos"+n+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class va{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new pa(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new ma(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new pa(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new ma(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const wa={};const ga=h.mat4(),Ea=h.mat4(),Ta=h.vec4([0,0,0,1]),ba=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]),h.OBB3();const Da=h.vec3(),Pa=h.vec3(),Ra=h.vec3(),Ca=h.vec3(),_a=h.vec3(),Ba=h.vec3(),Oa=h.vec3();class Sa{constructor(e){console.info("Creating TrianglesBatchingLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=$i[t];return s||(s=new Zi(e),$i[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete $i[t],s._destroy()}))),s}(e.model.scene),this._snapBatchingRenderers=function(e){const t=e.id;let s=wa[t];return s||(s=new va(e),wa[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete wa[t],s._destroy()}))),s}(e.model.scene),this._buffer=new ea(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Je({origin:h.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=h.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=h.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.aabb=h.collapseAABB3(),this.solid=!!e.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.normals,i=e.normalsCompressed,a=e.uv,r=e.uvCompressed,l=e.colors,o=e.colorsCompressed,c=e.indices,u=e.edgeIndices,p=e.color,A=e.metallic,d=e.roughness,f=e.opacity,I=e.meshMatrix,y=e.worldAABB,m=e.pickColor,v=this.model.scene,w=this._buffer,g=w.positions.length/3;let E;if(this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";E=s.length/3;for(let e=0,t=s.length;e<t;e++)w.positions.push(s[e]);const e=Bt.getPositionsBounds(s),t=Bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=Bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);y[0]=t[0],y[1]=t[1],y[2]=t[2],y[3]=n[0],y[4]=n[1],y[5]=n[2]}else{if(!t)throw"positions expected";E=t.length/3;const e=t.length,s=w.positions.length;for(let e=0,s=t.length;e<s;e++)w.positions.push(t[e]);if(I)for(let t=s,n=s+e;t<n;t+=3)Ta[0]=w.positions[t+0],Ta[1]=w.positions[t+1],Ta[2]=w.positions[t+2],h.transformPoint4(I,Ta,ba),w.positions[t+0]=ba[0],w.positions[t+1]=ba[1],w.positions[t+2]=ba[2],h.expandAABB3Point3(this._modelAABB,ba),h.expandAABB3Point3(y,ba);else for(let t=s,n=s+e;t<n;t+=3)Ta[0]=w.positions[t+0],Ta[1]=w.positions[t+1],Ta[2]=w.positions[t+2],h.expandAABB3Point3(this._modelAABB,Ta),h.expandAABB3Point3(y,Ta)}if(this._state.origin){const e=this._state.origin;y[0]+=e[0],y[1]+=e[1],y[2]+=e[2],y[3]+=e[0],y[4]+=e[1],y[5]+=e[2]}if(h.expandAABB3(this.aabb,y),i&&i.length>0)for(let e=0,t=i.length;e<t;e++)w.normals.push(i[e]);else if(n&&n.length>0){const e=ga;I?h.inverseMat4(h.transposeMat4(I,Ea),e):h.identityMat4(e,e),function(e,t,s,n,i){function a(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let r,l,o,c,u,p,A=new Float32Array([0,0,0,0]),d=new Float32Array([0,0,0,0]);for(p=0;p<s;p+=3)A[0]=t[p],A[1]=t[p+1],A[2]=t[p+2],h.transformVec3(e,A,d),h.normalizeVec3(d,d),o=r=aa(d,"floor","floor"),l=ra(r),c=u=a(d,l),r=aa(d,"ceil","floor"),l=ra(r),c=a(d,l),c>u&&(o=r,u=c),r=aa(d,"floor","ceil"),l=ra(r),c=a(d,l),c>u&&(o=r,u=c),r=aa(d,"ceil","ceil"),l=ra(r),c=a(d,l),c>u&&(o=r,u=c),n[i+p+0]=o[0],n[i+p+1]=o[1],n[i+p+2]=0}(e,n,n.length,w.normals,w.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)w.colors.push(255*l[e]),w.colors.push(255*l[e+1]),w.colors.push(255*l[e+2]),w.colors.push(255);else if(o)for(let e=0,t=l.length;e<t;e+=3)w.colors.push(l[e]),w.colors.push(l[e+1]),w.colors.push(l[e+2]),w.colors.push(255);else if(p){const e=p[0],t=p[1],s=p[2],n=f;for(let i=0;i<E;i++)w.colors.push(e),w.colors.push(t),w.colors.push(s),w.colors.push(n)}const T=null!=A?A:0,b=null!=d?d:255;for(let e=0;e<E;e++)w.metallicRoughness.push(T),w.metallicRoughness.push(b);if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)w.uv.push(a[e]);else if(r&&r.length>0)for(let e=0,t=r.length;e<t;e++)w.uv.push(r[e]);for(let e=0,t=c.length;e<t;e++)w.indices.push(g+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)w.edgeIndices.push(g+u[e]);{const e=w.pickColors.length;for(let t=e,s=e+4*E;t<s;t+=4)w.pickColors.push(m[0]),w.pickColors.push(m[1]),w.pickColors.push(m[2]),w.pickColors.push(m[3])}if(v.entityOffsetsEnabled)for(let e=0;e<E;e++)w.offsets.push(0),w.offsets.push(0),w.offsets.push(0);const D=this._portions.length,P={vertsBaseIndex:g,numVerts:E,indicesBaseIndex:w.indices.length-c.length,numIndices:c.length};return v.pickSurfacePrecisionEnabled&&(P.indices=c,v.entityOffsetsEnabled&&(P.offset=new Float32Array(3))),this._portions.push(P),this._numPortions++,this.model.numPortions++,this._numVerts+=P.numVerts,D}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0){const n=this._state.positionsDecodeMatrix?new Uint16Array(s.positions):na(s.positions,this._modelAABB,this._state.positionsDecodeMatrix=h.mat4());if(e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,n.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],s=3*t.vertsBaseIndex,i=s+3*t.numVerts;t.quantizedPositions=n.slice(s,i)}}if(s.normals.length>0){const n=new Int8Array(s.normals);let i=!0;e.normalsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.normals.length,3,t.STATIC_DRAW,i)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.uv.length>0)if(e.uvDecodeMatrix){let n=!1;e.uvBuf=new Oe(t,t.ARRAY_BUFFER,s.uv,s.uv.length,2,t.STATIC_DRAW,n)}else{const n=Bt.getUVBounds(s.uv),i=Bt.compressUVs(s.uv,n.min,n.max),a=i.quantized;let r=!1;e.uvDecodeMatrix=h.mat3(i.decodeMatrix),e.uvBuf=new Oe(t,t.ARRAY_BUFFER,a,a.length,2,t.STATIC_DRAW,r)}if(s.metallicRoughness.length>0){const n=new Uint8Array(s.metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Oe(t,t.ARRAY_BUFFER,n,s.metallicRoughness.length,2,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n),a=!1;e.flagsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}if(s.edgeIndices.length>0){const n=new Uint32Array(s.edgeIndices);e.edgeIndicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,n,s.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=e,n=this._portions[s],i=4*n.vertsBaseIndex,a=4*n.numVerts,r=this._scratchMemory.getUInt8Array(a),l=t[0],o=t[1],c=t[2],u=t[3];for(let e=0;e<a;e+=4)r[e+0]=l,r[e+1]=o,r[e+2]=c,r[e+3]=u;this._state.colorsBuf&&this._state.colorsBuf.setData(r,i,a)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=e,a=this._portions[i],r=a.vertsBaseIndex,l=a.numVerts,o=!!(t&Q),c=!!(t&X),u=!!(t&q),h=!!(t&J),p=!!(t&Z),A=!!(t&z),d=!!(t&W);let f,I;f=!o||d||c||u&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,I=!o||d?gi.NOT_RENDERED:h?gi.SILHOUETTE_SELECTED:u?gi.SILHOUETTE_HIGHLIGHTED:c?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let y=0;y=!o||d?gi.NOT_RENDERED:h?gi.EDGES_SELECTED:u?gi.EDGES_HIGHLIGHTED:c?gi.EDGES_XRAYED:p?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let m=o&&!d&&A?gi.PICK:gi.NOT_RENDERED;const v=t&K?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=r,t=r+l;e<t;e++){let t=0;t|=f,t|=I<<4,t|=y<<8,t|=m<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(l);for(let t=0;t<l;t++){let s=0;s|=f,s|=I<<4,s|=y<<8,s|=m<<12,s|=v<<16,e[t]=s}this._state.flagsBuf.setData(e,r,l)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=e,n=this._portions[s],i=3*n.vertsBaseIndex,a=3*n.numVerts,r=this._scratchMemory.getFloat32Array(a),l=t[0],o=t[1],c=t[2];for(let e=0;e<a;e+=3)r[e+0]=l,r[e+1]=o,r[e+2]=c;this._state.offsetsBuf&&this._state.offsetsBuf.setData(r,i,a),this.model.scene.pickSurfacePrecisionEnabled&&(n.offset[0]=t[0],n.offset[1]=t[1],n.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return;const s=this._state,n=this._portions[e];if(!n)return void this.model.error("portion not found: "+e);const i=n.quantizedPositions,a=s.origin,r=n.offset,l=a[0]+r[0],o=a[1]+r[1],c=a[2]+r[2],u=Ta;for(let e=0,n=i.length;e<n;e+=3)u[0]=i[e],u[1]=i[e+1],u[2]=i[e+2],u[3]=1,h.decompressPosition(u,s.positionsDecodeMatrix),h.transformPoint4(this.model.worldMatrix,u),u[0]+=l,u[1]+=o,u[2]+=c,t(u)}getElementsCountAndOffset(e){let t=null,s=null;const n=this._portions[e];return n&&(t=n.numIndices,s=n.indicesBaseIndex),{count:t,offset:s}}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRendererWithSAO&&this._batchingRenderers.pbrRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRendererWithSAO&&this._batchingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._batchingRenderers.flatColorRendererWithSAO&&this._batchingRenderers.flatColorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._batchingRenderers.pbrRenderer&&this._batchingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._batchingRenderers.colorTextureRenderer&&this._batchingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._state.normalsBuf?this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._batchingRenderers.flatColorRenderer&&this._batchingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsFlatRenderer&&this._batchingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,gi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthBufInitRenderer&&this._snapBatchingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,gi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapBatchingRenderers.snapDepthRenderer&&this._snapBatchingRenderers.snapDepthRenderer.drawLayer(t,this,gi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state,r=this._portions[e];if(!r)return this.model.error("portion not found: "+e),!1;const l=r.quantizedPositions,o=r.indices,c=a.origin,u=r.offset,p=Da,A=Pa;p.set(c?h.subVec3(t,c,Ra):t),A.set(s),u&&h.subVec3(p,u),h.transformRay(this.model.worldNormalMatrix,p,A,p,A);const d=Ca,f=_a,I=Ba;let y=!1,m=0;const v=Oa;for(let e=0,s=o.length;e<s;e+=3){const s=3*o[e],r=3*o[e+1],w=3*o[e+2];if(d[0]=l[s],d[1]=l[s+1],d[2]=l[s+2],f[0]=l[r],f[1]=l[r+1],f[2]=l[r+2],I[0]=l[w],I[1]=l[w+1],I[2]=l[w+2],h.decompressPosition(d,a.positionsDecodeMatrix),h.decompressPosition(f,a.positionsDecodeMatrix),h.decompressPosition(I,a.positionsDecodeMatrix),h.rayTriangleIntersect(p,A,d,f,I,v)){h.transformPoint3(this.model.worldMatrix,v,v),u&&h.addVec3(v,u),c&&h.addVec3(v,c);const e=Math.abs(h.lenVec3(h.subVec3(v,t,[])));(!y||e>m)&&(m=e,n.set(v),i&&h.triangleNormal(d,f,I,i),y=!0)}}return y&&i&&(h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),y}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Na extends Oi{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0;let i,a,r;const l=[];for(l.push("#version 300 es"),l.push("// Instancing geometry drawing vertex shader"),l.push("uniform int renderPass;"),l.push("in vec3 position;"),l.push("in vec2 normal;"),l.push("in vec4 color;"),l.push("in float flags;"),e.entityOffsetsEnabled&&l.push("in vec3 offset;"),l.push("in vec4 modelMatrixCol0;"),l.push("in vec4 modelMatrixCol1;"),l.push("in vec4 modelMatrixCol2;"),l.push("in vec4 modelNormalMatrixCol0;"),l.push("in vec4 modelNormalMatrixCol1;"),l.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(l,!0),e.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;")),l.push("uniform vec4 lightAmbient;"),i=0,a=s.lights.length;i<a;i++)r=s.lights[i],"ambient"!==r.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===r.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===r.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===r.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")));for(l.push("vec3 octDecode(vec2 oct) {"),l.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push(" if (v.z < 0.0) {"),l.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"),n&&(l.push("out vec4 vWorldPosition;"),l.push("out float vFlags;")),l.push("out vec4 vColor;"),l.push("void main(void) {"),l.push("int colorFlag = int(flags) & 0xF;"),l.push("if (colorFlag != renderPass) {"),l.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),l.push("} else {"),l.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),l.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix * worldPosition; "),l.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),l.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),l.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),i=0,a=s.lights.length;i<a;i++)if(r=s.lights[i],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}return l.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),l.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),l.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(l.push("vWorldPosition = worldPosition;"),l.push("vFlags = flags;")),l.push("gl_Position = clipPos;"),l.push("}"),l.push("}"),l}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):n.push(" outColor = vColor;"),n.push("}"),n}}class xa extends Oi{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry flat-shading drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState;let n,i;const a=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry flat-shading drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),a){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];"ambient"!==e.type&&(r.push("uniform vec4 lightColor"+n+";"),"dir"===e.type&&r.push("uniform vec3 lightDir"+n+";"),"point"===e.type&&r.push("uniform vec3 lightPos"+n+";"),"spot"===e.type&&(r.push("uniform vec3 lightPos"+n+";"),r.push("uniform vec3 lightDir"+n+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),a){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}for(r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),n=0,i=s.lights.length;n<i;n++){const e=s.lights[n];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?r.push("viewLightDir = -normalize(lightPos"+n+" - viewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+n+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?r.push("viewLightDir = normalize(lightDir"+n+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+n+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+n+".rgb * lightColor"+n+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);")):r.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class La extends Oi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing fill fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Ma extends Si{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("uniform vec4 color;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(color.r, color.g, color.b, color.a);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Fa extends Si{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Triangles instancing edges vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int edgeFlag = int(flags) >> 8 & 0xF;"),s.push("if (edgeFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class Ha extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry picking vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry picking fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class Ua extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Ga extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec2 normal;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("in vec4 modelNormalMatrixCol0;"),s.push("in vec4 modelNormalMatrixCol1;"),s.push("in vec4 modelNormalMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vWorldNormal;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),s.push(" vWorldNormal = worldNormal;"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vWorldNormal;"),n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class ja extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesInstancingOcclusionRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}class Va extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry depth drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec2 vHighPrecisionZW;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("vHighPrecisionZW = gl_Position.zw;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry depth drawing fragment shader"),a.push("precision highp float;"),a.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec2 vHighPrecisionZW;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),a.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),a.push("}"),a}}class ka extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec3 normal;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s,!0),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),s.push("vec3 octDecode(vec2 oct) {"),s.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),s.push(" if (v.z < 0.0) {"),s.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),s.push(" }"),s.push(" return normalize(v);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec3 vViewNormal;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),s.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" vViewNormal = viewNormal;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class Qa extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}const Wa={3e3:"linearToLinear",3001:"sRGBToLinear"};class za extends Oi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,s=e._lightsState,n=t.sectionPlanes.length>0,i=t.clippingCaps,a=[];return a.push("#version 300 es"),a.push("// Instancing geometry quality drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec3 normal;"),a.push("in vec4 color;"),a.push("in vec2 uv;"),a.push("in vec2 metallicRoughness;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),a.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("vec3 octDecode(vec2 oct) {"),a.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),a.push(" if (v.z < 0.0) {"),a.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),a.push("out vec4 vViewPosition;"),a.push("out vec3 vViewNormal;"),a.push("out vec4 vColor;"),a.push("out vec2 vUV;"),a.push("out vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("out vec3 vWorldNormal;"),n&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;"),i&&a.push("out vec4 vClipPosition;")),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push(" worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),a.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(a.push("vFragDepth = 1.0 + clipPos.w;"),a.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),n&&(a.push("vWorldPosition = worldPosition;"),a.push("vFlags = flags;"),i&&a.push("vClipPosition = clipPos;")),a.push("vViewPosition = viewPosition;"),a.push("vViewNormal = viewNormal;"),a.push("vColor = color;"),a.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),a.push("vMetallicRoughness = metallicRoughness;"),s.lightMaps.length>0&&a.push("vWorldNormal = worldNormal.xyz;"),a.push("gl_Position = clipPos;"),a.push("}"),a.push("}"),a}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState,i=s.sectionPlanes.length>0,a=s.clippingCaps,r=[];r.push("#version 300 es"),r.push("// Instancing geometry quality drawing fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform sampler2D uColorMap;"),r.push("uniform sampler2D uMetallicRoughMap;"),r.push("uniform sampler2D uEmissiveMap;"),r.push("uniform sampler2D uNormalMap;"),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),n.reflectionMaps.length>0&&r.push("uniform samplerCube reflectionMap;"),n.lightMaps.length>0&&r.push("uniform samplerCube lightMap;"),r.push("uniform vec4 lightAmbient;");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];"ambient"!==t.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("uniform float gammaFactor;"),r.push("vec4 linearToLinear( in vec4 value ) {"),r.push(" return value;"),r.push("}"),r.push("vec4 sRGBToLinear( in vec4 value ) {"),r.push(" 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.w );"),r.push("}"),r.push("vec4 gammaToLinear( in vec4 value) {"),r.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),r.push("}"),t&&(r.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),r.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;"),a&&r.push("in vec4 vClipPosition;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("in vec4 vViewPosition;"),r.push("in vec3 vViewNormal;"),r.push("in vec4 vColor;"),r.push("in vec2 vUV;"),r.push("in vec2 vMetallicRoughness;"),n.lightMaps.length>0&&r.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(r,!0),r.push("#define PI 3.14159265359"),r.push("#define RECIPROCAL_PI 0.31830988618"),r.push("#define RECIPROCAL_PI2 0.15915494"),r.push("#define EPSILON 1e-6"),r.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),r.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),r.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),r.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),r.push(" return normalize(surf_norm );"),r.push(" }"),r.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),r.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),r.push(" vec2 st0 = dFdx( uv.st );"),r.push(" vec2 st1 = dFdy( uv.st );"),r.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),r.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),r.push(" vec3 N = normalize( surf_norm );"),r.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),r.push(" mat3 tsn = mat3( S, T, N );"),r.push(" return normalize( tsn * mapN );"),r.push("}"),r.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),r.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),r.push("}"),r.push("struct IncidentLight {"),r.push(" vec3 color;"),r.push(" vec3 direction;"),r.push("};"),r.push("struct ReflectedLight {"),r.push(" vec3 diffuse;"),r.push(" vec3 specular;"),r.push("};"),r.push("struct Geometry {"),r.push(" vec3 position;"),r.push(" vec3 viewNormal;"),r.push(" vec3 worldNormal;"),r.push(" vec3 viewEyeDir;"),r.push("};"),r.push("struct Material {"),r.push(" vec3 diffuseColor;"),r.push(" float specularRoughness;"),r.push(" vec3 specularColor;"),r.push(" float shine;"),r.push("};"),r.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),r.push(" float r = ggxRoughness + 0.0001;"),r.push(" return (2.0 / (r * r) - 2.0);"),r.push("}"),r.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),r.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),r.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),r.push("}"),n.reflectionMaps.length>0&&(r.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),r.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),r.push(" vec3 envMapColor = "+Wa[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),r.push(" return envMapColor;"),r.push("}")),r.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),r.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),r.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),r.push("}"),r.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" return 1.0 / ( gl * gv );"),r.push("}"),r.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),r.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),r.push(" return 0.5 / max( gv + gl, EPSILON );"),r.push("}"),r.push("float D_GGX(const in float alpha, const in float dotNH) {"),r.push(" float a2 = ( alpha * alpha );"),r.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),r.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float alpha = ( roughness * roughness );"),r.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),r.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),r.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),r.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),r.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),r.push(" vec3 F = F_Schlick( specularColor, dotLH );"),r.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),r.push(" float D = D_GGX( alpha, dotNH );"),r.push(" return F * (G * D);"),r.push("}"),r.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),r.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),r.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),r.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),r.push(" vec4 r = roughness * c0 + c1;"),r.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),r.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),r.push(" return specularColor * AB.x + AB.y;"),r.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(r.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(r.push(" vec3 irradiance = "+Wa[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),r.push(" irradiance *= PI;"),r.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(r.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),r.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),r.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),r.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),r.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),r.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),r.push("}")),r.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),r.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),r.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),r.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");a?(r.push(" if (dist > (0.002 * vClipPosition.w)) {"),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" return;"),r.push("}")):(r.push(" if (dist > 0.0) { "),r.push(" discard;"),r.push(" }")),r.push("}")}r.push("IncidentLight light;"),r.push("Material material;"),r.push("Geometry geometry;"),r.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),r.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),r.push("float opacity = float(vColor.a) / 255.0;"),r.push("vec3 baseColor = rgb;"),r.push("float specularF0 = 1.0;"),r.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),r.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),r.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),r.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),r.push("baseColor *= colorTexel.rgb;"),r.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),r.push("metallic *= metalRoughTexel.b;"),r.push("roughness *= metalRoughTexel.g;"),r.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),r.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),r.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),r.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),r.push("geometry.position = vViewPosition.xyz;"),r.push("geometry.viewNormal = -normalize(viewNormal);"),r.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),n.lightMaps.length>0&&r.push("geometry.worldNormal = normalize(vWorldNormal);"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&r.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=n.lights.length;e<t;e++){const t=n.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?r.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?r.push("light.direction = normalize(lightDir"+e+");"):r.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),r.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return r.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),r.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),r.push("vec4 fragColor;"),this._withSAO?(r.push(" float viewportWidth = uSAOParams[0];"),r.push(" float viewportHeight = uSAOParams[1];"),r.push(" float blendCutoff = uSAOParams[2];"),r.push(" float blendFactor = uSAOParams[3];"),r.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),r.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),r.push(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):r.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&r.push("fragColor = linearToGamma(fragColor, gammaFactor);"),r.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}class Ka extends Oi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry normals vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s,3),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&s.push("out float vFlags;"),s.push("out vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&s.push("vFlags = flags;"),s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Batched geometry normals fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("in vec4 vWorldPosition;"),s){n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out highp ivec4 outNormal;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),n.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),n.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),n.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),n.push("}"),n}}class Ya extends Oi{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry drawing vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in vec2 uv;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("out vec4 vColor;"),s.push("out vec2 vUV;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vViewPosition = viewPosition;"),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),s.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,s=e._sectionPlanesState,n=e._lightsState;let i,a;const r=s.sectionPlanes.length>0,l=[];if(l.push("#version 300 es"),l.push("// Instancing geometry drawing fragment shader"),l.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),l.push("precision highp float;"),l.push("precision highp int;"),l.push("#else"),l.push("precision mediump float;"),l.push("precision mediump int;"),l.push("#endif"),e.logarithmicDepthBufferEnabled&&(l.push("in float isPerspective;"),l.push("uniform float logDepthBufFC;"),l.push("in float vFragDepth;")),l.push("uniform sampler2D uColorMap;"),this._withSAO&&(l.push("uniform sampler2D uOcclusionTexture;"),l.push("uniform vec4 uSAOParams;"),l.push("const float packUpscale = 256. / 255.;"),l.push("const float unpackDownScale = 255. / 256.;"),l.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),l.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),l.push("float unpackRGBToFloat( const in vec4 v ) {"),l.push(" return dot( v, unPackFactors );"),l.push("}")),l.push("uniform float gammaFactor;"),l.push("vec4 linearToLinear( in vec4 value ) {"),l.push(" return value;"),l.push("}"),l.push("vec4 sRGBToLinear( in vec4 value ) {"),l.push(" 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.w );"),l.push("}"),l.push("vec4 gammaToLinear( in vec4 value) {"),l.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),l.push("}"),t&&(l.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),l.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),l.push("}")),r){l.push("in vec4 vWorldPosition;"),l.push("in float vFlags;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("uniform bool sectionPlaneActive"+e+";"),l.push("uniform vec3 sectionPlanePos"+e+";"),l.push("uniform vec3 sectionPlaneDir"+e+";")}for(this._addMatricesUniformBlockLines(l),l.push("uniform vec4 lightAmbient;"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];"ambient"!==e.type&&(l.push("uniform vec4 lightColor"+i+";"),"dir"===e.type&&l.push("uniform vec3 lightDir"+i+";"),"point"===e.type&&l.push("uniform vec3 lightPos"+i+";"),"spot"===e.type&&(l.push("uniform vec3 lightPos"+i+";"),l.push("uniform vec3 lightDir"+i+";")))}if(l.push("in vec4 vViewPosition;"),l.push("in vec4 vColor;"),l.push("in vec2 vUV;"),l.push("out vec4 outColor;"),l.push("void main(void) {"),r){l.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),l.push(" if (clippable) {"),l.push(" float dist = 0.0;");for(let e=0,t=s.sectionPlanes.length;e<t;e++)l.push("if (sectionPlaneActive"+e+") {"),l.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),l.push("}");l.push(" if (dist > 0.0) { "),l.push(" discard;"),l.push(" }"),l.push("}")}for(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),l.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),l.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),l.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),i=0,a=n.lights.length;i<a;i++){const e=n.lights[i];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?l.push("viewLightDir = -normalize(lightPos"+i+" - viewPosition.xyz);"):l.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+i+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?l.push("viewLightDir = normalize(lightDir"+i+");"):l.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+i+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+i+".rgb * lightColor"+i+".a);")}}return l.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * vColor.rgb) + (reflectedColor * vColor.rgb), vColor.a);"),t?l.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));"):l.push("vec4 colorTexel = color * texture(uColorMap, vUV);"),l.push("float opacity = color.a;"),this._withSAO?(l.push(" float viewportWidth = uSAOParams[0];"),l.push(" float viewportHeight = uSAOParams[1];"),l.push(" float blendCutoff = uSAOParams[2];"),l.push(" float blendFactor = uSAOParams[3];"),l.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),l.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb * ambient, opacity);")):l.push(" outColor = vec4(vColor.rgb * colorTexel.rgb, opacity);"),t&&l.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&l.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),l.push("}"),l}}class Xa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new La(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Ha(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ua(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Na(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Na(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new xa(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new xa(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new za(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new za(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Ya(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Ya(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new La(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Va(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ka(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Ma(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Fa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ha(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ga(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ka(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ua(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ja(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Qa(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const qa={};const Ja=h.vec3(),Za=h.vec3(),$a=h.vec3(),er=h.vec3(),tr=h.mat4();class sr extends Ci{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.canvas.gl,r=i.camera,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||r.viewMatrix;this._vaoCache.has(t)?a.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=Ja;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=Za;if(o){const e=h.transformPoint3(u,o,$a);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,tr),y=er,y[0]=r.eye[0]-t[0],y[1]=r.eye[1]-t[1],y[2]=r.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=r.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;a.uniform3fv(this._uCameraEyeRtc,y),a.uniform2fv(this.uVectorA,e.snapVectorA),a.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),a.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),a.uniform3fv(this._uCoordinateScaler,f),a.uniform1i(this._uRenderPass,s),a.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(r.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),a.bindBuffer(a.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),a.bufferData(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,a.DYNAMIC_DRAW),a.bindBufferBase(a.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(l.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(l.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(l.modelMatrixCol2Buf),a.vertexAttribDivisor(this._aModelMatrixCol0.location,1),a.vertexAttribDivisor(this._aModelMatrixCol1.location,1),a.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(l.flagsBuf),a.vertexAttribDivisor(this._aFlags.location,1)),l.indicesBuf.bind(),a.drawElementsInstanced(a.TRIANGLES,l.indicesBuf.numItems,l.indicesBuf.itemType,0,l.numInstances),l.indicesBuf.unbind(),a.vertexAttribDivisor(this._aModelMatrixCol0.location,0),a.vertexAttribDivisor(this._aModelMatrixCol1.location,0),a.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&a.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&a.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthBufInitRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec4 pickColor;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),s.push("flat out vec4 vPickColor;"),s.push("out vec4 vWorldPosition;"),t&&s.push("out float vFlags;"),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vWorldPosition = worldPosition;"),t&&s.push(" vFlags = flags;"),s.push("vPickColor = pickColor;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),s.push("in vec4 vWorldPosition;"),s.push("flat in vec4 vPickColor;"),t){s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("layout(location = 0) out highp ivec4 outCoords;"),s.push("layout(location = 1) out highp ivec4 outNormal;"),s.push("layout(location = 2) out lowp uvec4 outPickColor;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" float dx = dFdx(vFragDepth);"),s.push(" float dy = dFdy(vFragDepth);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),s.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),s.push("outPickColor = uvec4(vPickColor);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const nr=h.vec3(),ir=h.vec3(),ar=h.vec3(),rr=h.vec3(),lr=h.mat4();class or extends Ci{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,s){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const n=t.model,i=n.scene,a=i.camera,r=i.canvas.gl,l=t._state,o=t._state.origin,{position:c,rotationMatrix:u,rotationMatrixConjugate:p}=n,A=t.aabb,d=e.pickViewMatrix||a.viewMatrix;this._vaoCache.has(t)?r.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));const f=nr;let I,y;if(f[0]=h.safeInv(A[3]-A[0])*h.MAX_INT,f[1]=h.safeInv(A[4]-A[1])*h.MAX_INT,f[2]=h.safeInv(A[5]-A[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(f[0]),e.snapPickCoordinateScale[1]=h.safeInv(f[1]),e.snapPickCoordinateScale[2]=h.safeInv(f[2]),o||0!==c[0]||0!==c[1]||0!==c[2]){const t=ir;if(o){const e=h.transformPoint3(u,o,ar);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=c[0],t[1]+=c[1],t[2]+=c[2],I=G(d,t,lr),y=rr,y[0]=a.eye[0]-t[0],y[1]=a.eye[1]-t[1],y[2]=a.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else I=d,y=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;r.uniform3fv(this._uCameraEyeRtc,y),r.uniform2fv(this.uVectorA,e.snapVectorA),r.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),r.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),r.uniform3fv(this._uCoordinateScaler,f),r.uniform1i(this._uRenderPass,s),r.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(p,0),this._matricesUniformBlockBufferData.set(I,m+=16),this._matricesUniformBlockBufferData.set(a.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(l.positionsDecodeMatrix,m+=16),r.bindBuffer(r.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),r.bufferData(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,r.DYNAMIC_DRAW),r.bindBufferBase(r.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(l.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(l.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(l.modelMatrixCol2Buf),r.vertexAttribDivisor(this._aModelMatrixCol0.location,1),r.vertexAttribDivisor(this._aModelMatrixCol1.location,1),r.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(l.flagsBuf),r.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(l.edgeIndicesBuf.bind(),r.drawElementsInstanced(r.LINES,l.edgeIndicesBuf.numItems,l.edgeIndicesBuf.itemType,0,l.numInstances),l.edgeIndicesBuf.unbind()):r.drawArraysInstanced(r.POINTS,0,l.positionsBuf.numItems,l.numInstances),r.vertexAttribDivisor(this._aModelMatrixCol0.location,0),r.vertexAttribDivisor(this._aModelMatrixCol1.location,0),r.vertexAttribDivisor(this._aModelMatrixCol2.location,0),r.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&r.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("precision highp usampler2D;"),s.push("precision highp isampler2D;"),s.push("precision highp sampler2D;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("precision mediump usampler2D;"),s.push("precision mediump isampler2D;"),s.push("precision mediump sampler2D;"),s.push("#endif"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec3 uCameraEyeRtc;"),s.push("uniform vec2 snapVectorA;"),s.push("uniform vec2 snapInvVectorAB;"),s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;"),s.push("bool isPerspectiveMatrix(mat4 m) {"),s.push(" return (m[2][3] == - 1.0);"),s.push("}"),s.push("out float isPerspective;"),s.push("vec2 remapClipPos(vec2 clipPos) {"),s.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),s.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),s.push(" return vec2(x, y);"),s.push("}"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out highp vec3 relativeToOriginPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("relativeToOriginPosition = worldPosition.xyz;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("float tmp = clipPos.w;"),s.push("clipPos.xyzw /= tmp;"),s.push("clipPos.xy = remapClipPos(clipPos.xy);"),s.push("clipPos.xyzw *= tmp;"),s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),s.push("gl_Position = clipPos;"),s.push("gl_PointSize = 1.0;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// SnapInstancingDepthRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"),s.push("uniform int layerNumber;"),s.push("uniform vec3 coordinateScaler;"),t){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("uniform bool sectionPlaneActive"+t+";"),s.push("uniform vec3 sectionPlanePos"+t+";"),s.push("uniform vec3 sectionPlaneDir"+t+";")}if(s.push("in highp vec3 relativeToOriginPosition;"),s.push("out highp ivec4 outCoords;"),s.push("void main(void) {"),t){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let t=0;t<e.sectionPlanes.length;t++)s.push("if (sectionPlaneActive"+t+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class cr{constructor(e){this._scene=e}_compile(){this._snapDepthBufInitRenderer&&!this._snapDepthBufInitRenderer.getValid()&&(this._snapDepthBufInitRenderer.destroy(),this._snapDepthBufInitRenderer=null),this._snapDepthRenderer&&!this._snapDepthRenderer.getValid()&&(this._snapDepthRenderer.destroy(),this._snapDepthRenderer=null)}eagerCreateRenders(){this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sr(this._scene,!1)),this._snapDepthRenderer||(this._snapDepthRenderer=new or(this._scene))}get snapDepthBufInitRenderer(){return this._snapDepthBufInitRenderer||(this._snapDepthBufInitRenderer=new sr(this._scene,!1)),this._snapDepthBufInitRenderer}get snapDepthRenderer(){return this._snapDepthRenderer||(this._snapDepthRenderer=new or(this._scene)),this._snapDepthRenderer}_destroy(){this._snapDepthBufInitRenderer&&this._snapDepthBufInitRenderer.destroy(),this._snapDepthRenderer&&this._snapDepthRenderer.destroy()}}const ur={};const hr=new Uint8Array(4),pr=new Float32Array(1),Ar=h.vec4([0,0,0,1]),dr=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]);const fr=new Float32Array(3),Ir=h.vec3(),yr=h.vec3(),mr=h.vec3(),vr=h.vec3(),wr=h.vec3(),gr=h.vec3(),Er=h.vec3(),Tr=new Float32Array(4);class br{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._instancingRenderers=function(e){const t=e.id;let s=qa[t];return s||(s=new Xa(e),qa[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete qa[t],s._destroy()}))),s}(e.model.scene),this._snapInstancingRenderers=function(e){const t=e.id;let s=ur[t];return s||(s=new cr(e),ur[t]=s,s._compile(),s.eagerCreateRenders(),e.on("compile",(()=>{s._compile(),s.eagerCreateRenders()})),e.on("destroyed",(()=>{delete ur[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Je({numInstances:0,obb:h.OBB3(),origin:h.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.aabb=h.collapseAABB3(),this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}createPortion(e){const t=e.color,s=e.metallic,n=e.roughness,i=null!==e.opacity&&void 0!==e.opacity?e.opacity:255,a=e.meshMatrix,r=e.aabb,l=e.pickColor;if(this._finalized)throw"Already finalized";const o=t[0],c=t[1],u=t[2];if(this._colors.push(o),this._colors.push(c),this._colors.push(u),this._colors.push(i),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=n?n:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(a[0]),this._modelMatrixCol0.push(a[4]),this._modelMatrixCol0.push(a[8]),this._modelMatrixCol0.push(a[12]),this._modelMatrixCol1.push(a[1]),this._modelMatrixCol1.push(a[5]),this._modelMatrixCol1.push(a[9]),this._modelMatrixCol1.push(a[13]),this._modelMatrixCol2.push(a[2]),this._modelMatrixCol2.push(a[6]),this._modelMatrixCol2.push(a[10]),this._modelMatrixCol2.push(a[14]),this._state.geometry.normals){let e=h.transposeMat4(a,h.mat4()),t=h.inverseMat4(e);this._modelNormalMatrixCol0.push(t[0]),this._modelNormalMatrixCol0.push(t[4]),this._modelNormalMatrixCol0.push(t[8]),this._modelNormalMatrixCol0.push(t[12]),this._modelNormalMatrixCol1.push(t[1]),this._modelNormalMatrixCol1.push(t[5]),this._modelNormalMatrixCol1.push(t[9]),this._modelNormalMatrixCol1.push(t[13]),this._modelNormalMatrixCol2.push(t[2]),this._modelNormalMatrixCol2.push(t[6]),this._modelNormalMatrixCol2.push(t[10]),this._modelNormalMatrixCol2.push(t[14])}this._pickColors.push(l[0]),this._pickColors.push(l[1]),this._pickColors.push(l[2]),this._pickColors.push(l[3]);const p=this._state.geometry.positionsCompressed.length,A=this._state.geometry.positionsCompressed,d=this._state.geometry.positionsDecodeMatrix;for(let e=0;e<p;e+=3)Ar[0]=A[e+0],Ar[1]=A[e+1],Ar[2]=A[e+2],h.transformPoint4(d,Ar,dr),h.transformPoint4(a,dr,Ar),h.expandAABB3Point3(r,Ar);if(this._state.origin){const e=this._state.origin;r[0]+=e[0],r[1]+=e[1],r[2]+=e[2],r[3]+=e[0],r[4]+=e[1],r[5]+=e[2]}h.expandAABB3(this.aabb,r),this._state.numInstances++;const f=this._portions.length,I={};return this.model.scene.pickSurfacePrecisionEnabled&&(I.matrix=a.slice(),I.inverseMatrix=null,I.normalMatrix=null),this._portions.push(I),this._numPortions++,this.model.numPortions++,f}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,s=e.textureSet,n=this.model.scene.canvas.gl,i=this._colors.length,a=i/4;if(i>0){let t=!1;e.colorsBuf=new Oe(n,n.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,n.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let s=!1;e.metallicRoughnessBuf=new Oe(n,n.ARRAY_BUFFER,t,this._metallicRoughness.length,2,n.STATIC_DRAW,s)}if(a>0){let t=!1;e.flagsBuf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(a),a,1,n.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,n.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const s=!1;e.positionsBuf=new Oe(n,n.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,n.STATIC_DRAW,s),e.positionsDecodeMatrix=h.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const s=new Uint8Array(t.colorsCompressed),i=!1;e.colorsBuf=new Oe(n,n.ARRAY_BUFFER,s,s.length,4,n.STATIC_DRAW,i)}if(t.uvCompressed&&t.uvCompressed.length>0){const s=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Oe(n,n.ARRAY_BUFFER,s,s.length,2,n.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,n.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Oe(n,n.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,n.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,n.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Oe(n,n.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,n.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Oe(n,n.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,n.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&s&&s.colorTexture&&s.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!s&&!!s.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";hr[0]=t[0],hr[1]=t[1],hr[2]=t[2],hr[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(hr,4*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&Q),i=!!(t&X),a=!!(t&q),r=!!(t&J),l=!!(t&Z),o=!!(t&z),c=!!(t&W);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,h=!n||c?gi.NOT_RENDERED:r?gi.SILHOUETTE_SELECTED:a?gi.SILHOUETTE_HIGHLIGHTED:i?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let p=0;p=!n||c?gi.NOT_RENDERED:r?gi.EDGES_SELECTED:a?gi.EDGES_HIGHLIGHTED:i?gi.EDGES_XRAYED:l?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?gi.PICK:gi.NOT_RENDERED)<<12,A|=(t&K?1:0)<<16,pr[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(pr,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(fr[0]=t[0],fr[1]=t[1],fr[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(fr,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const s=this._state,n=s.geometry,i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const a=n.quantizedPositions,r=s.origin,l=i.offset,o=r[0]+l[0],c=r[1]+l[1],u=r[2]+l[2],p=Ar,A=i.matrix,d=this.model.sceneModelMatrix,f=s.positionsDecodeMatrix;for(let e=0,s=a.length;e<s;e+=3)p[0]=a[e],p[1]=a[e+1],p[2]=a[e+2],h.decompressPosition(p,f),h.transformPoint3(A,p),h.transformPoint3(d,p),p[0]+=o,p[1]+=c,p[2]+=u,t(p)}setMatrix(e,t){if(!this._finalized)throw"Not finalized";var s=4*e;Tr[0]=t[0],Tr[1]=t[4],Tr[2]=t[8],Tr[3]=t[12],this._state.modelMatrixCol0Buf.setData(Tr,s),Tr[0]=t[1],Tr[1]=t[5],Tr[2]=t[9],Tr[3]=t[13],this._state.modelMatrixCol1Buf.setData(Tr,s),Tr[0]=t[2],Tr[1]=t[6],Tr[2]=t[10],Tr[3]=t[14],this._state.modelMatrixCol2Buf.setData(Tr,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRendererWithSAO&&this._instancingRenderers.pbrRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRendererWithSAO&&this._instancingRenderers.colorTextureRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):this._instancingRenderers.flatColorRendererWithSAO&&this._instancingRenderers.flatColorRendererWithSAO.drawLayer(t,this,gi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const s=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==s){const e=t.gl;s?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=s}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._instancingRenderers.pbrRenderer&&this._instancingRenderers.pbrRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._instancingRenderers.colorTextureRenderer&&this._instancingRenderers.colorTextureRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._state.normalsBuf?this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT):this._instancingRenderers.flatColorRenderer&&this._instancingRenderers.flatColorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,gi.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,gi.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,gi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsFlatRenderer&&this._instancingRenderers.pickNormalsFlatRenderer.drawLayer(t,this,gi.PICK))}drawSnapInitDepthBuf(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthBufInitRenderer&&this._snapInstancingRenderers.snapDepthBufInitRenderer.drawLayer(t,this,gi.PICK))}drawSnapDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._snapInstancingRenderers.snapDepthRenderer&&this._snapInstancingRenderers.snapDepthRenderer.drawLayer(t,this,gi.PICK))}precisionRayPickSurface(e,t,s,n,i){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const a=this._state.geometry,r=this._state,l=this._portions[e];if(!l)return this.model.error("portion not found: "+e),!1;l.inverseMatrix||(l.inverseMatrix=h.inverseMat4(l.matrix,h.mat4())),i&&!l.normalMatrix&&(l.normalMatrix=h.transposeMat4(l.inverseMatrix,h.mat4()));const o=a.quantizedPositions,c=a.indices,u=r.origin,p=l.offset,A=Ir,d=yr;A.set(u?h.subVec3(t,u,mr):t),d.set(s),p&&h.subVec3(A,p),h.transformRay(this.model.worldNormalMatrix,A,d,A,d),h.transformRay(l.inverseMatrix,A,d,A,d);const f=vr,I=wr,y=gr;let m=!1,v=0;const w=Er;for(let e=0,s=c.length;e<s;e+=3){const s=3*c[e+0],a=3*c[e+1],g=3*c[e+2];f[0]=o[s],f[1]=o[s+1],f[2]=o[s+2],I[0]=o[a],I[1]=o[a+1],I[2]=o[a+2],y[0]=o[g],y[1]=o[g+1],y[2]=o[g+2];const{positionsDecodeMatrix:E}=r.geometry;if(h.decompressPosition(f,E),h.decompressPosition(I,E),h.decompressPosition(y,E),h.rayTriangleIntersect(A,d,f,I,y,w)){h.transformPoint3(l.matrix,w,w),h.transformPoint3(this.model.worldMatrix,w,w),p&&h.addVec3(w,p),u&&h.addVec3(w,u);const e=Math.abs(h.lenVec3(h.subVec3(w,t,[])));(!m||e>v)&&(v=e,n.set(w),i&&h.triangleNormal(f,I,y,i),m=!0)}}return m&&i&&(h.transformVec3(l.normalMatrix,i,i),h.transformVec3(this.model.worldNormalMatrix,i,i),h.normalizeVec3(i)),m}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Dr extends Li{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Pr extends Li{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Rr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Dr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Cr={};class _r{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}const Br=h.vec4([0,0,0,1]),Or=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]),h.OBB3();class Sr{constructor(e){this.layerIndex=e.layerIndex,this._batchingRenderers=function(e){const t=e.id;let s=Cr[t];return s||(s=new Rr(e),Cr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Cr[t],s._destroy()}))),s}(e.model.scene),this.model=e.model,this._buffer=new _r(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Je({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._numVerts=0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.indices,i=e.color,a=e.opacity,r=e.meshMatrix,l=e.worldAABB;e.pickColor;const o=this._buffer,c=o.positions.length/3;let u;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";u=s.length/3;for(let e=0,t=s.length;e<t;e++)o.positions.push(s[e]);const e=Bt.getPositionsBounds(s),t=Bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,[]),n=Bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,[]);l[0]=t[0],l[1]=t[1],l[2]=t[2],l[3]=n[0],l[4]=n[1],l[5]=n[2]}else{if(!t)throw"positions expected";u=t.length/3;const e=t.length,s=o.positions.length;for(let e=0,s=t.length;e<s;e++)o.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)Br[0]=o.positions[t+0],Br[1]=o.positions[t+1],Br[2]=o.positions[t+2],h.transformPoint4(r,Br,Or),o.positions[t+0]=Or[0],o.positions[t+1]=Or[1],o.positions[t+2]=Or[2],h.expandAABB3Point3(this._modelAABB,Or),h.expandAABB3Point3(l,Or);else for(let t=s,n=s+e;t<n;t+=3)Br[0]=o.positions[t+0],Br[1]=o.positions[t+1],Br[2]=o.positions[t+2],h.expandAABB3Point3(this._modelAABB,Br),h.expandAABB3Point3(l,Br)}if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}if(h.expandAABB3(this.aabb,l),i){const e=i[0],t=i[1],s=i[2],n=a;for(let i=0;i<u;i++)o.colors.push(e),o.colors.push(t),o.colors.push(s),o.colors.push(n)}if(n)for(let e=0,t=n.length;e<t;e++)o.indices.push(n[e]+c);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<u;e++)o.offsets.push(0),o.offsets.push(0),o.offsets.push(0);const p=this._portions.length/2;return this._portions.push(c),this._portions.push(u),this._numPortions++,this.model.numPortions++,this._numVerts+=u,p}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=na(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.DYNAMIC_DRAW,i)}if(s.colors.length>0){const n=s.colors.length/4,i=new Float32Array(n);let a=!1;e.flagsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}if(s.indices.length>0){const n=new Uint32Array(s.indices);e.indicesBuf=new Oe(t,t.ELEMENT_ARRAY_BUFFER,n,s.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,s,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2],c=t[3];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o,a[e+3]=c;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s,n=!1){if(!this._finalized)throw"Not finalized";const i=2*e,a=this._portions[i],r=this._portions[i+1],l=!!(t&Q),o=!!(t&X),c=!!(t&q),u=!!(t&J),h=!!(t&z),p=!!(t&W);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,d=!l||p?gi.NOT_RENDERED:u?gi.SILHOUETTE_SELECTED:c?gi.SILHOUETTE_HIGHLIGHTED:o?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let f=l&&!p&&h?gi.PICK:gi.NOT_RENDERED;const I=t&K?1:0;if(n){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=a,t=a+r;e<t;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(r);for(let t=0;t<r;t++){let s=0;s|=A,s|=d<<4,s|=f<<12,s|=I<<16,e[t]=s}this._state.flagsBuf.setData(e,a,r)}}_setDeferredFlags(){this._deferredFlagValues&&(this._state.flagsBuf.setData(this._deferredFlagValues),this._deferredFlagValues=null)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicesBuf=null),e.destroy()}}class Nr extends Mi{drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 lightAmbient;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Lines instancing color fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("in vec4 vColor;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return this._withSAO?(a.push(" float viewportWidth = uSAOParams[0];"),a.push(" float viewportHeight = uSAOParams[1];"),a.push(" float blendCutoff = uSAOParams[2];"),a.push(" float blendFactor = uSAOParams[3];"),a.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),a.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):a.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class xr extends Mi{drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Lines instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("uniform vec4 color;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}class Lr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Nr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const Mr={};const Fr=new Uint8Array(4),Hr=new Float32Array(1),Ur=h.vec4([0,0,0,1]),Gr=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]);const jr=new Float32Array(3),Vr=new Float32Array(4);class kr{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let s=Mr[t];return s||(s=new Lr(e),Mr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete Mr[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Je({obb:h.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],e.origin&&(this._state.origin=h.vec3(e.origin)),this._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.color,s=e.opacity,n=e.meshMatrix,i=e.aabb;if(this._finalized)throw"Already finalized";const a=t[0],r=t[1],l=t[2];t[3],this._colors.push(a),this._colors.push(r),this._colors.push(l),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(n[0]),this._modelMatrixCol0.push(n[4]),this._modelMatrixCol0.push(n[8]),this._modelMatrixCol0.push(n[12]),this._modelMatrixCol1.push(n[1]),this._modelMatrixCol1.push(n[5]),this._modelMatrixCol1.push(n[9]),this._modelMatrixCol1.push(n[13]),this._modelMatrixCol2.push(n[2]),this._modelMatrixCol2.push(n[6]),this._modelMatrixCol2.push(n[10]),this._modelMatrixCol2.push(n[14]),h.collapseAABB3(i);const o=this._state.obb,c=o.length;for(let e=0;e<c;e+=4)Ur[0]=o[e+0],Ur[1]=o[e+1],Ur[2]=o[e+2],h.transformPoint4(n,Ur,Gr),h.expandAABB3Point3(i,Gr);if(this._state.origin){const e=this._state.origin;i[0]+=e[0],i[1]+=e[1],i[2]+=e[2],i[3]+=e[0],i[4]+=e[1],i[5]+=e[2]}h.expandAABB3(this.aabb,i),this._state.numInstances++;const u=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,u}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,s=t/4;if(t>0){let t=!1;this._state.colorsBuf=new Oe(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(s>0){let t=!1;this._state.flagsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fr[0]=t[0],Fr[1]=t[1],Fr[2]=t[2],Fr[3]=t[3],this._state.colorsBuf.setData(Fr,4*e,4)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&Q),i=!!(t&X),a=!!(t&q),r=!!(t&J),l=!!(t&Z),o=!!(t&z),c=!!(t&W);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,h=!n||c?gi.NOT_RENDERED:r?gi.SILHOUETTE_SELECTED:a?gi.SILHOUETTE_HIGHLIGHTED:i?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let p=0;p=!n||c?gi.NOT_RENDERED:r?gi.EDGES_SELECTED:a?gi.EDGES_HIGHLIGHTED:i?gi.EDGES_XRAYED:l?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?gi.PICK:gi.NOT_RENDERED)<<12,A|=(t&K?255:0)<<16,Hr[0]=A,this._state.flagsBuf.setData(Hr,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(jr[0]=t[0],jr[1]=t[1],jr[2]=t[2],this._state.offsetsBuf.setData(jr,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;Vr[0]=t[0],Vr[1]=t[4],Vr[2]=t[8],Vr[3]=t[12],this._state.modelMatrixCol0Buf.setData(Vr,s),Vr[0]=t[1],Vr[1]=t[5],Vr[2]=t[9],Vr[3]=t[13],this._state.modelMatrixCol1Buf.setData(Vr,s),Vr[0]=t[2],Vr[1]=t[6],Vr[2]=t[10],Vr[3]=t[14],this._state.modelMatrixCol2Buf.setData(Vr,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Qr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial,n=[];return n.push("#version 300 es"),n.push("// Points batching color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push(" if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class Wr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform vec4 color;"),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points batching silhouette vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("uniform vec4 color;"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push(" if (dist > 0.0) { discard; }"),a.push("}")}return e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("outColor = color;"),a.push("}"),a}}class zr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching pick mesh vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var i=0;i<t.sectionPlanes.length;i++)n.push("uniform bool sectionPlaneActive"+i+";"),n.push("uniform vec3 sectionPlanePos"+i+";"),n.push("uniform vec3 sectionPlaneDir"+i+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vPickColor; "),n.push("}"),n}}class Kr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batched pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("gl_PointSize += 10.0;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batched pick depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var i=0;i<t.sectionPlanes.length;i++)n.push(" if (sectionPlaneActive"+i+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class Yr extends Ni{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points batching occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push(" } else {"),n.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push(" gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push(" }"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching occlusion fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push(" if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push(" }");n.push(" if (dist > 0.0) { discard; }"),n.push(" }")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),n.push("}"),n}}class Xr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Qr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Wr(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new zr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Kr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Yr(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const qr={};class Jr{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}const Zr=h.vec4(),$r=h.vec4(),el=h.vec4([0,0,0,1]),tl=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]),h.OBB3();class sl{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let s=qr[t];return s||(s=new Xr(e),qr[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete qr[t],s._destroy()}))),s}(e.model.scene),this._buffer=new Jr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new Je({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:h.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=h.collapseAABB3(),this._portions=[],this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=h.vec3(e.origin)),this.aabb=h.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,s=e.positionsCompressed,n=e.color,i=e.colorsCompressed,a=e.colors,r=e.meshMatrix,l=e.worldAABB,o=e.pickColor,c=this._buffer,u=c.positions.length/3;let p;if(this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";for(let e=0,t=s.length;e<t;e++)c.positions.push(s[e]);const e=Bt.getPositionsBounds(s),t=Bt.decompressPosition(e.min,this._state.positionsDecodeMatrix,Zr),n=Bt.decompressPosition(e.max,this._state.positionsDecodeMatrix,$r);l[0]=t[0],l[1]=t[1],l[2]=t[2],l[3]=n[0],l[4]=n[1],l[5]=n[2],p=s.length/3}else{if(!t)throw"positions expected";p=t.length/3;const e=t.length,s=c.positions.length;for(let e=0,s=t.length;e<s;e++)c.positions.push(t[e]);if(r)for(let t=s,n=s+e;t<n;t+=3)el[0]=c.positions[t+0],el[1]=c.positions[t+1],el[2]=c.positions[t+2],h.transformPoint4(r,el,tl),c.positions[t+0]=tl[0],c.positions[t+1]=tl[1],c.positions[t+2]=tl[2],h.expandAABB3Point3(this._modelAABB,tl),h.expandAABB3Point3(l,tl);else for(let t=s,n=s+e;t<n;t+=3)el[0]=c.positions[t+0],el[1]=c.positions[t+1],el[2]=c.positions[t+2],h.expandAABB3Point3(this._modelAABB,el),h.expandAABB3Point3(l,el)}if(this._state.origin){const e=this._state.origin;l[0]+=e[0],l[1]+=e[1],l[2]+=e[2],l[3]+=e[0],l[4]+=e[1],l[5]+=e[2]}if(h.expandAABB3(this.aabb,l),i)for(let e=0,t=i.length;e<t;e++)c.colors.push(i[e]);else if(a)for(let e=0,t=a.length;e<t;e++)c.colors.push(255*a[e]);else if(n){const e=n[0],t=n[1],s=n[2],i=1;for(let n=0;n<p;n++)c.colors.push(e),c.colors.push(t),c.colors.push(s),c.colors.push(i)}{const e=c.pickColors.length;for(let t=e,s=e+4*p;t<s;t+=4)c.pickColors.push(o[0]),c.pickColors.push(o[1]),c.pickColors.push(o[2]),c.pickColors.push(o[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<p;e++)c.offsets.push(0),c.offsets.push(0),c.offsets.push(0);const A=this._portions.length/2;return this._portions.push(u),this._portions.push(p),this._numPortions++,this.model.numPortions++,A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,s=this._buffer;if(s.positions.length>0)if(this._preCompressedPositionsExpected){const n=new Uint16Array(s.positions);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}else{const n=na(new Float32Array(s.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.positions.length,3,t.STATIC_DRAW)}if(s.colors.length>0){const n=new Uint8Array(s.colors);let i=!1;e.colorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.colors.length,4,t.STATIC_DRAW,i)}if(s.positions.length>0){const n=s.positions.length/3,i=new Float32Array(n);let a=!1;e.flagsBuf=new Oe(t,t.ARRAY_BUFFER,i,i.length,1,t.DYNAMIC_DRAW,a)}if(s.pickColors.length>0){const n=new Uint8Array(s.pickColors);let i=!1;e.pickColorsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.pickColors.length,4,t.STATIC_DRAW,i)}if(this.model.scene.entityOffsetsEnabled&&s.offsets.length>0){const n=new Float32Array(s.offsets);e.offsetsBuf=new Oe(t,t.ARRAY_BUFFER,n,s.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";const s=2*e,n=4*this._portions[s],i=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=4)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.colorsBuf.setData(a,n,i)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=2*e,i=this._portions[n],a=this._portions[n+1],r=this._scratchMemory.getFloat32Array(a),l=!!(t&Q),o=!!(t&X),c=!!(t&q),u=!!(t&J),h=!!(t&z),p=!!(t&W);let A,d;A=!l||p||o||c&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,d=!l||p?gi.NOT_RENDERED:u?gi.SILHOUETTE_SELECTED:c?gi.SILHOUETTE_HIGHLIGHTED:o?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let f=l&&!p&&h?gi.PICK:gi.NOT_RENDERED;const I=t&K?1:0;for(let e=0;e<a;e++){let t=0;t|=A,t|=d<<4,t|=f<<12,t|=I<<16,r[e]=t}this._state.flagsBuf.setData(r,i)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const s=2*e,n=3*this._portions[s],i=3*this._portions[s+1],a=this._scratchMemory.getFloat32Array(i),r=t[0],l=t[1],o=t[2];for(let e=0;e<i;e+=3)a[e+0]=r,a[e+1]=l,a[e+2]=o;this._state.offsetsBuf.setData(a,n,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class nl extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing color vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec4 color;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),s.filterIntensity&&n.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),s.filterIntensity&&(n.push("float intensity = float(color.a) / 255.0;"),n.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {")),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),s.filterIntensity&&n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class il extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,s){super.drawLayer(e,t,s,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing silhouette vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 color;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),n.push("uniform vec4 silhouetteColor;"),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),n.push("if (silhouetteFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vColor;"),n.push("}"),n}}class al extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick mesh vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 pickColor;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vPickColor;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),n.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick mesh fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vPickColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = vPickColor; "),n.push("}"),n}}class rl extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing pick depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(n),this._addRemapClipPosLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vViewPosition;"),n.push("void main(void) {"),n.push("int pickFlag = int(flags) >> 12 & 0xF;"),n.push("if (pickFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push(" vFlags = flags;")),n.push(" vViewPosition = viewPosition;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),n.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = remapClipPos(clipPos);"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing pick depth fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform float pickZNear;"),n.push("uniform float pickZFar;"),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec4 vViewPosition;"),n.push("vec4 packDepth(const in float depth) {"),n.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),n.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),n.push(" vec4 res = fract(depth * bitShift);"),n.push(" res -= res.xxyz * bitMask;"),n.push(" return res;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),n.push(" outColor = packDepth(zNormalizedDepth); "),n.push("}"),n}}class ll extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 color;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push(" vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing occlusion vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("out vec4 outColor;"),n.push("void main(void) {"),e.pointsMaterial.roundPoints&&(n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }")),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return n.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class ol extends xi{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=e.pointsMaterial._state,n=[];return n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in float flags;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(n),n.push("uniform float pointSize;"),s.perspectivePoints&&n.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;")),t&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;")),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("gl_Position = clipPos;"),s.perspectivePoints?(n.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),n.push("gl_PointSize = max(gl_PointSize, "+Math.floor(s.minPerspectivePointSize)+".0);"),n.push("gl_PointSize = min(gl_PointSize, "+Math.floor(s.maxPerspectivePointSize)+".0);")):n.push("gl_PointSize = pointSize;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let s,n;const i=t.sectionPlanes.length>0,a=[];if(a.push("#version 300 es"),a.push("// Points instancing depth vertex shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),i)for(a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("uniform bool sectionPlaneActive"+s+";"),a.push("uniform vec3 sectionPlanePos"+s+";"),a.push("uniform vec3 sectionPlaneDir"+s+";");if(a.push("const float packUpScale = 256. / 255.;"),a.push("const float unpackDownscale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),a.push("const float shiftRight8 = 1.0 / 256.;"),a.push("vec4 packDepthToRGBA( const in float v ) {"),a.push(" vec4 r = vec4( fract( v * packFactors ), v );"),a.push(" r.yzw -= r.xyz * shiftRight8;"),a.push(" return r * packUpScale;"),a.push("}"),a.push("out vec4 outColor;"),a.push("void main(void) {"),e.pointsMaterial.roundPoints&&(a.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push(" float r = dot(cxy, cxy);"),a.push(" if (r > 1.0) {"),a.push(" discard;"),a.push(" }")),i){for(a.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;"),s=0,n=t.sectionPlanes.length;s<n;s++)a.push("if (sectionPlaneActive"+s+") {"),a.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),a.push("}");a.push("if (dist > 0.0) { discard; }"),a.push("}")}return a.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&a.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}}class cl extends xi{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,s=[];return s.push("#version 300 es"),s.push("// Instancing geometry shadow drawing vertex shader"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("bool visible = (colorFlag > 0);"),s.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),s.push("if (!visible || transparent) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s.push("gl_PointSize = pointSize;"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,s=t.sectionPlanes.length>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("in vec3 vViewNormal;"),n.push("vec3 packNormalToRGB( const in vec3 normal ) {"),n.push(" return normalize( normal ) * 0.5 + 0.5;"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push(" float r = dot(cxy, cxy);"),n.push(" if (r > 1.0) {"),n.push(" discard;"),n.push(" }"),s){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,s=t.sectionPlanes.length;e<s;e++)n.push("if (sectionPlaneActive"+e+") {"),n.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),n.push("}");n.push("if (dist > 0.0) { discard; }"),n.push("}")}return e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),n.push("}"),n}}class ul{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new il(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ol(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new al(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new rl(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ll(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new cl(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const hl={};const pl=new Uint8Array(4),Al=new Float32Array(1),dl=h.vec4([0,0,0,1]),fl=h.vec4([0,0,0,1]);h.vec4([0,0,0,1]);const Il=new Float32Array(3),yl=new Float32Array(4);class ml{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let s=hl[t];return s||(s=new ul(e),hl[t]=s,s._compile(),e.on("compile",(()=>{s._compile()})),e.on("destroyed",(()=>{delete hl[t],s._destroy()}))),s}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new Je({obb:h.OBB3(),numInstances:0,origin:e.origin?h.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._finalized=!1,this.aabb=h.collapseAABB3()}createPortion(e){const t=e.meshMatrix,s=e.aabb,n=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(n[0]),this._pickColors.push(n[1]),this._pickColors.push(n[2]),this._pickColors.push(n[3]),h.collapseAABB3(s);const i=this._state.obb,a=i.length;for(let e=0;e<a;e+=4)dl[0]=i[e+0],dl[1]=i[e+1],dl[2]=i[e+2],h.transformPoint4(t,dl,fl),h.expandAABB3Point3(s,fl);if(this._state.origin){const e=this._state.origin;s[0]+=e[0],s[1]+=e[1],s[2]+=e[2],s[3]+=e[0],s[4]+=e[1],s[5]+=e[2]}h.expandAABB3(this.aabb,s),this._state.numInstances++;const r=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,r}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4,s=this._state,n=s.geometry;if(t>0){let n=!1;s.flagsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,n)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;s.offsetsBuf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(n.positionsCompressed&&n.positionsCompressed.length>0){const t=!1;s.positionsBuf=new Oe(e,e.ARRAY_BUFFER,n.positionsCompressed,n.positionsCompressed.length,3,e.STATIC_DRAW,t),s.positionsDecodeMatrix=h.mat4(n.positionsDecodeMatrix)}if(n.colorsCompressed&&n.colorsCompressed.length>0){const t=new Uint8Array(n.colorsCompressed),i=!1;s.colorsBuf=new Oe(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,i)}if(this._modelMatrixCol0.length>0){const t=!1;s.modelMatrixCol0Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),s.modelMatrixCol1Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),s.modelMatrixCol2Buf=new Oe(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;s.pickColorsBuf=new Oe(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}s.geometry=null,this._finalized=!0}initFlags(e,t,s){t&Q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&q&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&X&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&J&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&K&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Z&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&z&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&W&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),s&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,s)}setVisible(e,t,s){if(!this._finalized)throw"Not finalized";t&Q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,s)}setHighlighted(e,t,s){if(!this._finalized)throw"Not finalized";t&q?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,s)}setXRayed(e,t,s){if(!this._finalized)throw"Not finalized";t&X?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,s)}setSelected(e,t,s){if(!this._finalized)throw"Not finalized";t&J?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,s)}setEdges(e,t,s){if(!this._finalized)throw"Not finalized";t&Z?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,s)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&K?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,s){if(!this._finalized)throw"Not finalized";t&z?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,s)}setCulled(e,t,s){if(!this._finalized)throw"Not finalized";t&W?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,s)}setColor(e,t){if(!this._finalized)throw"Not finalized";pl[0]=t[0],pl[1]=t[1],pl[2]=t[2],this._state.colorsBuf.setData(pl,3*e)}setTransparent(e,t,s){s?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,s)}_setFlags(e,t,s){if(!this._finalized)throw"Not finalized";const n=!!(t&Q),i=!!(t&X),a=!!(t&q),r=!!(t&J),l=!!(t&Z),o=!!(t&z),c=!!(t&W);let u,h;u=!n||c||i||a&&!this.model.scene.highlightMaterial.glowThrough||r&&!this.model.scene.selectedMaterial.glowThrough?gi.NOT_RENDERED:s?gi.COLOR_TRANSPARENT:gi.COLOR_OPAQUE,h=!n||c?gi.NOT_RENDERED:r?gi.SILHOUETTE_SELECTED:a?gi.SILHOUETTE_HIGHLIGHTED:i?gi.SILHOUETTE_XRAYED:gi.NOT_RENDERED;let p=0;p=!n||c?gi.NOT_RENDERED:r?gi.EDGES_SELECTED:a?gi.EDGES_HIGHLIGHTED:i?gi.EDGES_XRAYED:l?s?gi.EDGES_COLOR_TRANSPARENT:gi.EDGES_COLOR_OPAQUE:gi.NOT_RENDERED;let A=0;A|=u,A|=h<<4,A|=p<<8,A|=(n&&!c&&o?gi.PICK:gi.NOT_RENDERED)<<12,A|=(t&K?255:0)<<16,Al[0]=A,this._state.flagsBuf.setData(Al,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Il[0]=t[0],Il[1]=t[1],Il[2]=t[2],this._state.offsetsBuf.setData(Il,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const s=4*e;yl[0]=t[0],yl[1]=t[4],yl[2]=t[8],yl[3]=t[12],this._state.modelMatrixCol0Buf.setData(yl,s),yl[0]=t[1],yl[1]=t[5],yl[2]=t[9],yl[3]=t[13],this._state.modelMatrixCol1Buf.setData(yl,s),yl[0]=t[2],yl[1]=t[6],yl[2]=t[10],yl[3]=t[14],this._state.modelMatrixCol2Buf.setData(yl,s)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,gi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,gi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,gi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,gi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,gi.PICK)}drawPickNormals(e,t){}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}class vl{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class wl{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const gl={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class El{constructor(e,t,s){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=s}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,s=this.handlers.length;t<s;t+=2){const s=this.handlers[t],n=this.handlers[t+1];if(s.global&&(s.lastIndex=0),s.test(e))return n}return null}}const Tl=new El;class bl{constructor(e){this.manager=void 0!==e?e:Tl,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const s=this;return new Promise((function(n,i){s.load(e,n,t,i)}))}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}}const Dl={};class Pl extends bl{constructor(e){super(e)}load(e,t,s,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=gl.get(e);if(void 0!==i)return this.manager.itemStart(e),setTimeout((()=>{t&&t(i),this.manager.itemEnd(e)}),0),i;if(void 0!==Dl[e])return void Dl[e].push({onLoad:t,onProgress:s,onError:n});Dl[e]=[],Dl[e].push({onLoad:t,onProgress:s,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),r=this.mimeType,l=this.responseType;fetch(a).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const s=Dl[e],n=t.body.getReader(),i=t.headers.get("Content-Length"),a=i?parseInt(i):0,r=0!==a;let l=0;const o=new ReadableStream({start(e){!function t(){n.read().then((({done:n,value:i})=>{if(n)e.close();else{l+=i.byteLength;const n=new ProgressEvent("progress",{lengthComputable:r,loaded:l,total:a});for(let e=0,t=s.length;e<t;e++){const t=s[e];t.onProgress&&t.onProgress(n)}e.enqueue(i),t()}}))}()}});return new Response(o)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(l){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r)));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),s=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(s);return e.arrayBuffer().then((e=>n.decode(e)))}}})).then((t=>{gl.add(e,t);const s=Dl[e];delete Dl[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const s=Dl[e];if(void 0===s)throw this.manager.itemError(e),t;delete Dl[e];for(let e=0,n=s.length;e<n;e++){const n=s[e];n.onError&&n.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Rl{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 s=this.workersResolve[e];if(s&&s(t),this.queue.length){const{resolve:t,msg:s,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(s,n)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((s=>{const n=this._getIdleWorker();-1!==n?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=s,this.workers[n].postMessage(e,t)):this.queue.push({resolve:s,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let Cl=0;class _l{constructor({viewer:e,transcoderPath:t,workerLimit:s}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Rl,this._workerSourceURL="",s&&this._workerPool.setWorkerLimit(s);const n=e.capabilities;this._workerConfig={astcSupported:n.astcSupported,etc1Supported:n.etc1Supported,etc2Supported:n.etc2Supported,dxtSupported:n.dxtSupported,bptcSupported:n.bptcSupported,pvrtcSupported:n.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new Pl;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),s=new Pl;s.setPath(this._transcoderPath),s.setResponseType("arraybuffer"),s.setWithCredentials(this.withCredentials);const n=s.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,n]).then((([e,t])=>{const s=_l.BasisWorker.toString(),n=["/* constants */","let _EngineFormat = "+JSON.stringify(_l.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(_l.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(_l.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([n])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),Cl>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Cl++}return this._transcoderPending}transcode(e,t,s={}){return new Promise(((n,i)=>{const a=s;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:a},e))).then((e=>{const s=e.data,{mipmaps:a,width:r,height:l,format:o,type:c,error:u,dfdTransferFn:h,dfdFlags:p}=s;if("error"===c)return i(u);t.setCompressedData({mipmaps:a,props:{format:o,minFilter:1===a.length?1006:1008,magFilter:1===a.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&p)}}),n()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Cl--}}_l.BasisFormat={ETC1S:0,UASTC_4x4:1},_l.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},_l.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},_l.BasisWorker=function(){let e,t,s;const n=_EngineFormat,i=_TranscoderFormat,a=_BasisFormat;self.addEventListener("message",(function(r){const u=r.data;switch(u.type){case"init":e=u.config,h=u.transcoderBinary,t=new Promise((e=>{s={wasmBinary:h,onRuntimeInitialized:e},BASIS(s)})).then((()=>{s.initializeBasis(),void 0===s.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f}=function(t){const r=new s.KTX2File(new Uint8Array(t));function u(){r.close(),r.delete()}if(!r.isValid())throw u(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=r.isUASTC()?a.UASTC_4x4:a.ETC1S,p=r.getWidth(),A=r.getHeight(),d=r.getLevels(),f=r.getHasAlpha(),I=r.getDFDTransferFunc(),y=r.getDFDFlags(),{transcoderFormat:m,engineFormat:v}=function(t,s,r,u){let h,p;const A=t===a.ETC1S?l:o;for(let n=0;n<A.length;n++){const i=A[n];if(e[i.if]&&(i.basisFormat.includes(t)&&!(u&&i.transcoderFormat.length<2)&&(!i.needsPowerOfTwo||c(s)&&c(r))))return h=i.transcoderFormat[u?1:0],p=i.engineFormat[u?1:0],{transcoderFormat:h,engineFormat:p}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=i.RGBA32,p=n.RGBAFormat,{transcoderFormat:h,engineFormat:p}}(h,p,A,f);if(!p||!A||!d)throw u(),new Error("KTX2TextureTranscoder: Invalid texture");if(!r.startTranscoding())throw u(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const w=[];for(let e=0;e<d;e++){const t=r.getImageLevelInfo(e,0,0),s=t.origWidth,n=t.origHeight,i=new Uint8Array(r.getImageTranscodedSizeInBytes(e,0,0,m));if(!r.transcodeImage(i,e,0,0,m,0,-1,-1))throw u(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");w.push({data:i,width:s,height:n})}return u(),{width:p,height:A,hasAlpha:f,mipmaps:w,format:v,dfdTransferFn:I,dfdFlags:y}}(u.buffers[0]),I=[];for(let e=0;e<p.length;++e)I.push(p[e].data.buffer);self.postMessage({type:"transcode",id:u.id,width:t,height:r,hasAlpha:h,mipmaps:p,format:A,dfdTransferFn:d,dfdFlags:f},I)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:u.id,error:e.message})}}))}var h}));const r=[{if:"astcSupported",basisFormat:[a.UASTC_4x4],transcoderFormat:[i.ASTC_4x4,i.ASTC_4x4],engineFormat:[n.RGBA_ASTC_4x4_Format,n.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC7_M5,i.BC7_M5],engineFormat:[n.RGBA_BPTC_Format,n.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.BC1,i.BC3],engineFormat:[n.RGB_S3TC_DXT1_Format,n.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1,i.ETC2],engineFormat:[n.RGB_ETC2_Format,n.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.ETC1],engineFormat:[n.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[a.ETC1S,a.UASTC_4x4],transcoderFormat:[i.PVRTC1_4_RGB,i.PVRTC1_4_RGBA],engineFormat:[n.RGB_PVRTC_4BPPV1_Format,n.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],l=r.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),o=r.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function c(e){return e<=2||0==(e&e-1)&&0!==e}};const Bl={};function Ol(e){const t=e.scene.id;let s=Bl[t];return s||(s=new _l({viewer:e}),Bl[t]=s,e.scene.on("destroyed",(()=>{delete Bl[t],s.destroy()}))),s}
2
2
  /**
3
3
  * @author https://github.com/tmarti, with support from https://tribia.com/
4
4
  * @license MIT