@xeokit/xeokit-sdk 2.6.86 → 2.6.87

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,7 +1,7 @@
1
1
  /**
2
- * xeokit-sdk v2.6.86
3
- * Commit: c22de6eea11109e60991b4c31f0fb66792c24e2e
4
- * Built: 2025-07-29T15:17:36.560Z
2
+ * xeokit-sdk v2.6.87
3
+ * Commit: 8fcdaeda55a3bd75b49a6cc6fe5d950fa3251f38
4
+ * Built: 2025-07-31T17:46:22.388Z
5
5
  */
6
6
 
7
7
  "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 i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let o=!0,n=o?Float64Array:Float32Array;const a=new n(3),l=new n(16),A=new n(16),c=new n(4),h={setDoublePrecisionEnabled(e){o=e,n=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(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 n(e||16),mat4ToMat3:(e,t=new n(9))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t),doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r<o;r++)h.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble(e,t){const i=n.from([e])[0],s=e-i;t[0]=i,t[1]=s},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,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,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],compareVec4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3],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,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i<e.length;i++)t[0]+=e[i][0],t[1]+=e[i][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},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 n(3);return(t,i)=>h.lenVec3(h.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(h.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>h.lenVec2(h.subVec2(t,i,e))})(),rcpVec3:(e,t)=>h.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/h.lenVec4(e);return h.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/h.lenVec3(e);return h.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/h.lenVec2(e);return h.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=h.dotVec3(e,t)/Math.sqrt(h.sqLenVec3(e)*h.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=h.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=h.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=h.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);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 n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>h.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>h.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(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 n(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,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>h.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],_=e[15],v=t[0],b=t[1],y=t[2],w=t[3],B=t[4],x=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],T=t[12],D=t[13],S=t[14],R=t[15];return i[0]=v*s+b*a+y*h+w*f,i[1]=v*r+b*l+y*u+w*m,i[2]=v*o+b*A+y*d+w*g,i[3]=v*n+b*c+y*p+w*_,i[4]=B*s+x*a+P*h+C*f,i[5]=B*r+x*l+P*u+C*m,i[6]=B*o+x*A+P*d+C*g,i[7]=B*n+x*c+P*p+C*_,i[8]=M*s+F*a+E*h+I*f,i[9]=M*r+F*l+E*u+I*m,i[10]=M*o+F*A+E*d+I*g,i[11]=M*n+F*c+E*p+I*_,i[12]=T*s+D*a+S*h+R*f,i[13]=T*r+D*l+S*u+R*m,i[14]=T*o+D*A+S*d+R*g,i[15]=T*n+D*c+S*p+R*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],c=e[2],h=e[5],u=e[8],d=t[0],p=t[3],f=t[6],m=t[1],g=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*m+o*v,i[3]=s*p+r*g+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*m+A*v,i[4]=a*p+l*g+A*b,i[7]=a*f+l*_+A*y,i[2]=c*d+h*m+u*v,i[5]=c*p+h*g+u*b,i[8]=c*f+h*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=h.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],c=e[6],h=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=A,e[13]=h,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}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],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],c=e[9],h=e[10],u=e[11],d=e[12],p=e[13],f=e[14],m=e[15];return d*c*a*r-A*p*a*r-d*n*h*r+o*p*h*r+A*n*f*r-o*c*f*r-d*c*s*l+A*p*s*l+d*i*h*l-t*p*h*l-A*i*f*l+t*c*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*m+o*c*s*m+A*i*a*m-t*c*a*m-o*i*h*m+t*n*h*m},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],c=e[8],h=e[9],u=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,w=s*A-o*a,B=r*A-o*l,x=c*f-h*p,P=c*m-u*p,C=c*g-d*p,M=h*m-u*f,F=h*g-d*f,E=u*g-d*m,I=1/(_*E-v*F+b*M+y*C-w*P+B*x);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*B-m*w+g*y)*I,t[3]=(-h*B+u*w-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*B+m*b-g*v)*I,t[7]=(c*B-u*b+d*v)*I,t[8]=(n*F-a*C+A*x)*I,t[9]=(-i*F+s*C-o*x)*I,t[10]=(p*w-f*b+g*_)*I,t[11]=(-c*w+h*b-d*_)*I,t[12]=(-n*M+a*P-l*x)*I,t[13]=(i*M-s*P+r*x)*I,t[14]=(-p*y+f*v-m*_)*I,t[15]=(c*y-h*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||h.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||h.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,h.translationMat4v(e,r))})(),translationMat4s:(e,t)=>h.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>h.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=h.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let c,u,d,p,f,m;return c=a*l,u=l*A,d=A*a,p=a*r,f=l*r,m=A*r,(i=i||h.mat4())[0]=n*a*a+o,i[1]=n*c+m,i[2]=n*d-f,i[3]=0,i[4]=n*c-m,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>h.rotationMat4v(e,[t,i,s],r),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 n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,h.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>h.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=h.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,c=s*a,u=s*l,d=s*A,p=r*l,f=r*A,m=o*A,g=n*a,_=n*l,v=n*A;return i[0]=1-(p+m),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(c+m),i[6]=f+g,i[7]=0,i[8]=d+_,i[9]=f-g,i[10]=1-(c+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=h.vec4()){const s=h.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],c=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-c,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i[0]*=h.RADTODEG,i[1]*=h.RADTODEG,i[2]*=h.RADTODEG,i},composeMat4:(e,t,i,s=h.mat4())=>(h.quaternionToRotationMat4(t,s),h.scaleMat4v(i,s),h.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=h.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=h.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=h.lenVec3(e);h.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,c=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=u,t[9]*=u,t[10]*=u,h.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=h.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],c=t[0],u=t[1],d=t[2];if(r===c&&o===u&&n===d)return h.identityMat4();let p,f,m,g,_,v,b,y,w,B;return p=r-c,f=o-u,m=n-d,B=1/Math.sqrt(p*p+f*f+m*m),p*=B,f*=B,m*=B,g=l*m-A*f,_=A*p-a*m,v=a*f-l*p,B=Math.sqrt(g*g+_*_+v*v),B?(B=1/B,g*=B,_*=B,v*=B):(g=0,_=0,v=0),b=f*v-m*_,y=m*g-p*v,w=p*_-f*g,B=Math.sqrt(b*b+y*y+w*w),B?(B=1/B,b*=B,y*=B,w*=B):(b=0,y=0,w=0),s[0]=g,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=w,s[10]=m,s[11]=0,s[12]=-(g*r+_*o+v*n),s[13]=-(b*r+y*o+w*n),s[14]=-(p*r+f*o+m*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>h.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=h.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=h.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];h.addVec4(r,s,l),h.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],c=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/c,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/c,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=h.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],h.frustumMat4v(o,n,r)},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,i=h.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=h.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],c=e[1],h=e[2],u=e[3],d=e[4],p=e[5],f=e[6],m=e[7],g=e[8],_=e[9],v=e[10],b=e[11],y=e[12],w=e[13],B=e[14],x=e[15];let P;for(let e=0;e<r;++e)l=t[e],o=l[0],n=l[1],a=l[2],P=s[e]||(s[e]=[0,0,0]),P[0]=A*o+d*n+g*a+y,P[1]=c*o+p*n+_*a+w,P[2]=h*o+f*n+v*a+B,P[3]=u*o+m*n+b*a+x;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2];e[3];const h=e[4],u=e[5],d=e[6];e[7];const p=e[8],f=e[9],m=e[10];e[11];const g=e[12],_=e[13],v=e[14];for(e[15],s=0;s<r;s+=3)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+h*n+p*a+g,i[s+1]=A*o+u*n+f*a+_,i[s+2]=c*o+d*n+m*a+v;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2],h=e[3],u=e[4],d=e[5],p=e[6],f=e[7],m=e[8],g=e[9],_=e[10],v=e[11],b=e[12],y=e[13],w=e[14],B=e[15];for(s=0;s<r;s+=4)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+u*n+m*a+b,i[s+1]=A*o+d*n+g*a+y,i[s+2]=c*o+p*n+_*a+w,i[s+3]=h*o+f*n+v*a+B;return i},transformVec3(e,t,i){const s=t[0],r=t[1],o=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*o,i[1]=e[1]*s+e[5]*r+e[9]*o,i[2]=e[2]*s+e[6]*r+e[10]*o,i},transformVec4(e,t,i){const s=t[0],r=t[1],o=t[2],n=t[3];return(i=i||h.vec4())[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},rotateVec2(e,t,i,s=e){const r=Math.cos(i),o=Math.sin(i),n=e[0]-t[0],a=e[1]-t[1];return s[0]=n*r-a*o+t[0],s[1]=n*o+a*r+t[1],e},rotateVec3X(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0],o[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),o[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Y(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),o[1]=r[1],o[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Z(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),o[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),o[2]=r[2],s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},projectVec4(e,t){const i=1/e[3];return(t=t||h.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(()=>{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||h.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||h.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i<s;i++)for(n=e[i],r=0,o=n.length;r<o;r++)t.push(n[r]);return t},identityQuaternion:(e=h.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=h.vec4()){const s=e[0]*h.DEGTORAD/2,r=e[1]*h.DEGTORAD/2,o=e[2]*h.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),c=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*c*u,i[1]=n*c*l-A*a*u,i[2]=n*a*u+A*c*l,i[3]=n*a*l-A*c*u):"YXZ"===t?(i[0]=A*a*l+n*c*u,i[1]=n*c*l-A*a*u,i[2]=n*a*u-A*c*l,i[3]=n*a*l+A*c*u):"ZXY"===t?(i[0]=A*a*l-n*c*u,i[1]=n*c*l+A*a*u,i[2]=n*a*u+A*c*l,i[3]=n*a*l-A*c*u):"ZYX"===t?(i[0]=A*a*l-n*c*u,i[1]=n*c*l+A*a*u,i[2]=n*a*u-A*c*l,i[3]=n*a*l+A*c*u):"YZX"===t?(i[0]=A*a*l+n*c*u,i[1]=n*c*l+A*a*u,i[2]=n*a*u-A*c*l,i[3]=n*a*l-A*c*u):"XZY"===t&&(i[0]=A*a*l-n*c*u,i[1]=n*c*l-A*a*u,i[2]=n*a*u+A*c*l,i[3]=n*a*l+A*c*u),i},mat4ToQuaternion(e,t=h.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],c=e[10];let u;const d=i+n+c;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>c?(u=2*Math.sqrt(1+i-n-c),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>c?(u=2*Math.sqrt(1+n-i-c),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+c-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=h.vec4()){const s=Math.sqrt(h.dotVec3(e,e)*h.dotVec3(t,t));let r=s+h.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):h.cross3Vec3(e,t,i),i[3]=r,h.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=h.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||h.vec3(),h.quaternionToRotationMat4(t,e),h.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=h.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],c=t[3];return i[0]=n*a+s*c+r*A-o*l,i[1]=n*l+r*c+o*a-s*A,i[2]=n*A+o*c+s*l-r*a,i[3]=n*c-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=h.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],c=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=c*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-c*-l,i[2]=d*A+p*-l+c*-a-u*-n,i},quaternionToMat4(e,t){t=h.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,c=a*o,u=l*o,d=n*i,p=a*i,f=l*i,m=a*s,g=l*s,_=l*r;return t[0]=1-(m+_),t[1]=p+u,t[2]=f-c,t[4]=p-u,t[5]=1-(d+_),t[6]=g+A,t[8]=f+c,t[9]=g-A,t[10]=1-(d+m),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,c=i*a,h=i*l,u=s*a,d=s*l,p=r*l,f=o*n,m=o*a,g=o*l;return t[0]=1-(u+p),t[4]=c-g,t[8]=h+m,t[1]=c+g,t[5]=1-(A+p),t[9]=d-f,t[2]=h-m,t[6]=d+f,t[10]=1-(A+u),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 i=h.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,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 i=(e=h.normalizeQuaternion(e,c))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],c=e[2],h=e[3],u=e[4],d=e[5],p=e[6],f=e[7],m=e[8],g=e[9],_=e[10],v=e[11],b=e[12],y=e[13],w=e[14],B=e[15];for(s=0;s<r;s+=4)o=t[s+0],n=t[s+1],a=t[s+2],i[s+0]=l*o+u*n+m*a+b,i[s+1]=A*o+d*n+g*a+y,i[s+2]=c*o+p*n+_*a+w,i[s+3]=h*o+f*n+v*a+B;return i},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 n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],h.subVec3(t,e,i),Math.abs(h.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=h.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],c=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=c>u?c:u,Math.abs(h.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||h.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||h.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},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 n(3);return(t,i,s)=>{i=i||h.AABB3();let r,o,n,a=h.MAX_DOUBLE,l=h.MAX_DOUBLE,A=h.MAX_DOUBLE,c=h.MIN_DOUBLE,u=h.MIN_DOUBLE,d=h.MIN_DOUBLE;for(let i=0,p=t.length;i<p;i+=3)s?(e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2],h.decompressPosition(e,s,e),r=e[0],o=e[1],n=e[2]):(r=t[i+0],o=t[i+1],n=t[i+2]),r<a&&(a=r),o<l&&(l=o),n<A&&(A=n),r>c&&(c=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=c,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=h.AABB3()){let i,s,r,o=h.MAX_DOUBLE,n=h.MAX_DOUBLE,a=h.MAX_DOUBLE,l=h.MIN_DOUBLE,A=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)i=e[t+0],s=e[t+1],r=e[t+2],i<o&&(o=i),s<n&&(n=s),r<a&&(a=r),i>l&&(l=i),s>A&&(A=s),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=c,t},points3ToAABB3(e,t=h.AABB3()){let i,s,r,o=h.MAX_DOUBLE,n=h.MAX_DOUBLE,a=h.MAX_DOUBLE,l=h.MIN_DOUBLE,A=h.MIN_DOUBLE,c=h.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)i=e[t][0],s=e[t][1],r=e[t][2],i<o&&(o=i),s<n&&(n=s),r<a&&(a=r),i>l&&(l=i),s>A&&(A=s),r>c&&(c=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=c,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||h.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;s<a;s++)r+=t[s][0],o+=t[s][1],n+=t[s][2];i[0]=r/a,i[1]=o/a,i[2]=n/a;let l,A=0;for(s=0;s<a;s++)l=Math.abs(h.lenVec3(h.subVec3(t[s],i,e))),l>A&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||h.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;r<l;r+=3)o+=i[r],n+=i[r+1],a+=i[r+2];const c=l/3;let u;for(s[0]=o/c,s[1]=n/c,s[2]=a/c,r=0;r<l;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],u=Math.abs(h.lenVec3(h.subVec3(e,s,t))),u>A&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||h.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;r<l;r+=4)o+=i[r+0],n+=i[r+1],a+=i[r+2];s[0]=o/A,s[1]=n/A,s[2]=a/A;let c,u=0;for(r=0;r<l;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],c=Math.abs(h.lenVec3(h.subVec3(e,s,t))),c>u&&(u=c);return s[3]=u,s}})(),getSphere3Center:(e,t=h.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=h.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o<n;o+=3)i+=e[o+0],s+=e[o+1],r+=e[o+2];const a=e.length/3;return t[0]=i/a,t[1]=s/a,t[2]=r/a,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 i,s,r,o=0,n=t.length;o<n;o+=3)i=t[o],s=t[o+1],r=t[o+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);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],point3AABB3AbsoluteIntersect:(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,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=h.AABB2()){let i,s,r,o,n=h.MAX_DOUBLE,a=h.MAX_DOUBLE,l=h.MIN_DOUBLE,A=h.MIN_DOUBLE;for(let t=0,c=e.length;t<c;t+=4)i=e[t+0],s=e[t+1],r=e[t+3]||1,o=1/r,i*=o,s*=o,i<n&&(n=i),s<a&&(a=s),i>l&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,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,i,s=e){const r=.5*(e[0]+1),o=.5*(e[1]+1),n=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(n*t),s[3]=i-Math.floor(o*i),s},tangentQuadraticBezier:(e,t,i,s)=>2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,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,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=h.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],c=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(c*c+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,c)=>{c=c||h.vec3();const u=h.subVec3(l,a,e),d=h.subVec3(A,a,t),p=h.cross3Vec3(n,d,i),f=h.dotVec3(u,p);if(f<1e-6)return null;const m=h.subVec3(o,a,s),g=h.dotVec3(m,p);if(g<0||g>f)return null;const _=h.cross3Vec3(m,u,r),v=h.dotVec3(n,_);if(v<0||g+v>f)return null;const b=h.dotVec3(d,_)/f;return c[0]=o[0]+b*n[0],c[1]=o[1]+b*n[1],c[2]=o[2]+b*n[2],c}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||h.vec3(),o=h.normalizeVec3(o,e);const c=h.subVec3(a,n,t),u=h.subVec3(l,n,i),d=h.cross3Vec3(c,u,s);h.normalizeVec3(d,d);const p=-h.dotVec3(n,d),f=-(h.dotVec3(r,d)+p)/h.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=h.subVec3(n,r,e),A=h.subVec3(o,r,t),c=h.subVec3(s,r,i),u=h.dotVec3(l,l),d=h.dotVec3(l,A),p=h.dotVec3(l,c),f=h.dotVec3(A,A),m=h.dotVec3(A,c),g=u*f-d*d;if(0===g)return null;const _=1/g,v=(f*p-d*m)*_,b=(u*m-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=h.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let c,h,u,d;const p=1e4;let f,m,g=0;for(f=0,m=e.length;f<m;f+=3)c=e[f],h=e[f+1],u=e[f+2],d=`${Math.round(c*p)}_${Math.round(h*p)}_${Math.round(u*p)}`,void 0===r[d]&&(r[d]=n.length/3,n.push(c),n.push(h),n.push(u),t&&(a.push(t[f]),a.push(t[f+1]),a.push(t[f+2])),i&&(l.push(i[g]),l.push(i[g+1]))),o[f/3]=r[d],g+=2;for(f=0,m=s.length;f<m;f++)A[f]=o[s[f]];const _={positions:n,indices:A};return a&&(_.normals=a),l&&(_.uv=l),_},buildNormals:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,c;const u=new Array(n.length/3);let d,p,f,m,g,_,v;for(A=0,c=a.length;A<c;A+=3){d=a[A],p=a[A+1],f=a[A+2],e[0]=n[3*d],e[1]=n[3*d+1],e[2]=n[3*d+2],t[0]=n[3*p],t[1]=n[3*p+1],t[2]=n[3*p+2],i[0]=n[3*f],i[1]=n[3*f+1],i[2]=n[3*f+2],h.subVec3(t,e,s),h.subVec3(i,e,r);const l=h.vec3();h.normalizeVec3(h.cross3Vec3(s,r,o),l),u[d]||(u[d]=[]),u[p]||(u[p]=[]),u[f]||(u[f]=[]),u[d].push(l),u[p].push(l),u[f].push(l)}for(l=l&&l.length===n.length?l:new Float32Array(n.length),A=0,c=u.length;A<c;A++){m=u[A].length,g=0,_=0,v=0;for(let e=0;e<m;e++)g+=u[A][e][0],_+=u[A][e][1],v+=u[A][e][2];l[3*A]=g/m,l[3*A+1]=_/m,l[3*A+2]=v/m}return l}})(),buildTangents:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const c=new Float32Array(n.length);for(let u=0;u<l.length;u+=3){let d=l[u];const p=n.subarray(3*d,3*d+3),f=A.subarray(2*d,2*d+2);d=l[u+1];const m=n.subarray(3*d,3*d+3),g=A.subarray(2*d,2*d+2);d=l[u+2];const _=n.subarray(3*d,3*d+3),v=A.subarray(2*d,2*d+2),b=h.subVec3(m,p,e),y=h.subVec3(_,p,t),w=h.subVec2(g,f,i),B=h.subVec2(v,f,s),x=1/(w[0]*B[1]-w[1]*B[0]),P=h.mulVec3Scalar(h.subVec3(h.mulVec3Scalar(b,B[1],r),h.mulVec3Scalar(y,w[1],o),a),x,o);let C;for(let e=0;e<3;e++)C=3*l[u+e],c[C]+=P[0],c[C+1]+=P[1],c[C+2]+=P[2]}return c}})(),buildPickTriangles(e,t,i){const s=t.length,r=i?new Uint16Array(9*s):new Float32Array(9*s),o=new Uint8Array(12*s);let n,a,l,A,c,h,u=0,d=0,p=0;for(let i=0;i<s;i+=3)h=u>>24&255,c=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=c,o[p++]=h,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,c,u;const d=1e4;let p,f,m,g,_,v;for(f=0,g=e.length;f<g;f+=3){p=f/3,l=e[f],A=e[f+1],c=e[f+2],u=`${Math.round(l*d)}_${Math.round(A*d)}_${Math.round(c*d)}`,void 0===r[u]?r[u]=[p]:r[u].push(p);const i=h.normalizeVec3([t[f],t[f+1],t[f+2]]);o[p]=i,a=h.vec4([i[0],i[1],i[2],1]),n[p]=a}for(u in r)if(r.hasOwnProperty(u)){const e=r[u],t=e.length;for(f=0;f<t;f++){const i=e[f];for(a=n[i],m=0;m<t;m++){if(f===m)continue;const t=e[m];_=o[i],v=o[t];Math.abs(h.angleVec3(_,v)/h.DEGTORAD)<s&&(a[0]+=v[0],a[1]+=v[1],a[2]+=v[2],a[3]+=1)}}}for(f=0,g=t.length;f<g;f+=3)a=n[f/3],t[f+0]=a[0]/a[3],t[f+1]=a[1]/a[3],t[f+2]=a[2]/a[3]},transformRay:(()=>{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,h.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],h.transformVec3(i,e,t),h.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(4),i=new n(4),s=(t,i,s,r,o)=>{o[0]=t,o[1]=i,o[2]=s,o[3]=1,h.transformVec4(e,o,o),r||h.mulVec4Scalar(o,1/o[3])};return(r,o,n,a,l,A,c)=>{const u="ortho"===a;h.mulMat4(n,o,e),h.inverseMat4(e,e);const d=2*l[0]/r.clientWidth-1,p=1-2*l[1]/r.clientHeight;s(d,p,-1,u,t),s(d,p,1,u,i),A[0]=t[0],A[1]=t[1],A[2]=t[2],h.subVec3(i,t,c),h.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l,A)=>{h.canvasPosToWorldRay(i,s,r,o,a,e,t),h.worldRayToLocalRay(n,e,t,l,A)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=h.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,h.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],h.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,c;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,c=i.length;A<c;++A){var h=3*i[A];for(let e=0;e<3;++e){const t=3*s[h+e];r[t]<a[0]&&(a[0]=r[t]),r[t]>a[3]&&(a[3]=r[t]),r[t+1]<a[1]&&(a[1]=r[t+1]),r[t+1]>a[4]&&(a[4]=r[t+1]),r[t+2]<a[2]&&(a[2]=r[t+2]),r[t+2]>a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const m=new Array(i.length);let g=0;for(A=0,c=i.length;A<c;++A){const e=s[h=3*i[A]],t=3*s[h+1],o=3*s[h+2];r[3*e+u]<=d||r[t+u]<=d||r[o+u]<=d?p[f++]=i[A]:m[g++]=i[A]}return p.length=f,m.length=g,l.left=t(p,s,r,o+1),l.right=t(m,s,r,o+1),l}return(e,i)=>{const s=e.length/3,r=new Array(s);for(let e=0;e<s;++e)r[e]=e;return t(r,e,i,0)}})(),decompressPosition(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const n=1-Math.abs(r)-Math.abs(o);n<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};h.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=h.vec3(),c=h.vec3(),u=h.vec3(),d=h.vec3(),p=h.vec3(),f=h.vec3(),m=h.vec3();return function(g,_,v,b){!function(r,o){const n={};let a,l,A,c;const h=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;u<d;u+=3)a=r[u],l=r[u+1],A=r[u+2],c=Math.round(a*h)+"_"+Math.round(l*h)+"_"+Math.round(A*h),void 0===n[c]&&(n[c]=p/3,e[p++]=a,e[p++]=l,e[p++]=A),t[u/3]=n[c];for(u=0,d=o.length;u<d;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,_),function(t,i){o=0;for(let g=0,_=t;g<_;g+=3){const t=3*s[g],_=3*s[g+1],v=3*s[g+2];i?(n[0]=e[t],n[1]=e[t+1],n[2]=e[t+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(n,i,A),h.decompressPosition(a,i,c),h.decompressPosition(l,i,u)):(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],u[0]=e[v],u[1]=e[v+1],u[2]=e[v+2]),h.subVec3(u,c,d),h.subVec3(A,c,p),h.cross3Vec3(d,p,f),h.normalizeVec3(f,m);const b=r[o]||(r[o]={normal:h.vec3()});b.normal[0]=m[0],b.normal[1]=m[1],b.normal[2]=m[2],o++}}(_.length,v);const y=[],w=Math.cos(h.DEGTORAD*b),B={};let x,P,C,M,F,E,I,T,D,S,R,U=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)x=s[e+i],P=s[e+(i+1)%3],C=Math.min(x,P),M=Math.max(x,P),F=C+","+M,void 0===B[F]?B[F]={index1:C,index2:M,face1:t,face2:void 0}:B[F].face2=t}for(F in B)E=B[F],void 0!==E.face2&&(I=r[E.face1].normal,T=r[E.face2].normal,D=h.dotVec3(I,T),D>w)||(S=i[E.index1],R=i[E.index2],(!U&&S>65535||R>65535)&&(U=!0),y.push(S),y.push(R));return U?new Uint32Array(y):new Uint16Array(y)}}(),h.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r<o;r+=s){if(a[0]=i[r+0]-e[0],a[1]=i[r+1]-e[1],a[2]=i[r+2]-e[2],a[0]*t[0]+a[1]*t[1]+a[2]*t[2]<0)return!0}return!1};const u=new Float32Array(3);class d{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 p={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=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function m(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 g=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}();const _={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var o=0;o<t.attributes.length;o++){var n=t.attributes[o];r[i[n.nodeName]||n.nodeName]=n.nodeValue}for(var a=0;a<t.childNodes.length;a++){(o=e(t.childNodes[a],i))&&r.children.push(o)}return r}},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 m(t[0],2)+[1,4,7,10,13].map((function(e){return m((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[],s=function(e){e.type===t&&i.push(e),(e.children||[]).forEach((function(e){s(e)}))};return s(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(e){4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=e=>{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n<o.length;n++)i[n]=o.charCodeAt(n);M.scheduleTask((()=>{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:g,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 _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.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 _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r<o;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},v={},b=new e,y=new d,w={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},B=[];let x,P=0,C=0;const M=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(M.scenes[e.id])return void console.error(`[ERROR] Scene ${_.inQuotes(e.id)} already exists`)}else e.id=b.addItem({});M.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;v[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},p.components.scenes++,e.once("destroyed",(()=>{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s<e);)t=y.shift(),i=y.shift(),i?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return y.length}},F=function(){let e=Date.now();if(x=e-P,P>0&&x>0){var t=1e3/x;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{F()}),100);const E=function(){let e=Date.now();if(x=e-P,P>0&&x>0){var t=1e3/x;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}I(e),function(e){for(var t in w.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];w.sceneId=t,w.startTime=i.startTime,w.deltaTime=null!=w.prevTime?w.time-w.prevTime:0,i.fire("tick",w,!0)}w.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(F):requestAnimationFrame(E)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}E();class T{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 T))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,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}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+" "+_.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 i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,c,h;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,c=0,h=A.length;c<h;c++)l.off(A[c]);delete this._attached[t],delete this._attachments[l.id];const s=e.params.onDetached;s&&(_.isFunction(s)?s(l):s.scope?s.callback.call(s.scope,l):s.callback(l)),e.managingLifecycle&&l.destroy()}if(i){const s={params:e,component:i,subs:[],managingLifecycle:false};s.subs.push(i.once("destroyed",(function(){s.params.component=null,this._attach(s.params)}),this)),a&&s.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=s;const r=e.onAttached;if(r&&(_.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),n){let e,t,r,o;for(e in n)if(n.hasOwnProperty(e)){if(t=n[e],_.isFunction(t)?(r=t,o=null):(r=t.callback,o=t.scope),!r)continue;s.subs.push(i.on(e,r,o))}}}return a&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!_.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(!_.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 i=0,s=e.length;i<s;i++)if(e[i]===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():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_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,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r<o;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(i=this._ownedComponents[e],i.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 D=h.vec3(),S=h.vec3(),R=h.mat4();class U{constructor(){this.normal=h.vec3(),this.offset=0,this.testVertex=h.vec3()}set(e,t,i,s){const r=1/Math.sqrt(e*e+t*t+i*i);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=i*r,this.offset=s*r,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 L{constructor(){this.planes=[new U,new U,new U,new U,new U,new U]}}function k(e,t,i){const s=h.mulMat4(i,t,R),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],c=s[6],u=s[7],d=s[8],p=s[9],f=s[10],m=s[11],g=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,m-d,b-g),e.planes[1].set(a+r,u+l,m+d,b+g),e.planes[2].set(a-o,u-A,m-p,b-_),e.planes[3].set(a+o,u+A,m+p,b+_),e.planes[4].set(a-n,u-c,m-f,b-v),e.planes[5].set(a+n,u+c,m+f,b+v)}function O(e,t){let i=L.INSIDE;const s=D,r=S;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return L.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=L.INTERSECT)}return i}L.INSIDE=0,L.INTERSECT=1,L.OUTSIDE=2;class N extends T{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 L,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!==N.PICK_MODE_INSIDE&&e!==N.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===N.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=(i,s=L.INTERSECT)=>{if(s===L.INTERSECT&&(s=O(this._marqueeFrustum,i.aabb)),s!==L.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i<s;i++){const s=t[i];if(!s.visible)continue;const r=s.aabb;if(this._pickMode===N.PICK_MODE_INSIDE){O(this._marqueeFrustum,r)===L.INSIDE&&e.push(s.id)}else{O(this._marqueeFrustum,r)!==L.OUTSIDE&&e.push(s.id)}}}i.left&&t(i.left,s),i.right&&t(i.right,s)}};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,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,c=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);h.frustumMat4(l,A,c*a,u*a,d,1e4,this._marqueeFrustumProjMat),k(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)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class V{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class Q{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 i=this._messages[this._locale];if(!i)return null;const s=H(e,i);return s?t?G(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=H(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=G(r,[t]),i&&(r=G(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function H(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e<t;e++){s=s[i[e]]}return s}function G(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}class j extends T{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 i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=h.subVec3(o,r,[]);return h.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_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,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=h.lenVec3(h.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class z extends j{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 i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=h.vec3();return A[0]=h.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=h.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=h.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}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 W=h.vec3();const X=h.vec3(),K=h.vec3(),Z=h.vec3(),J=h.vec3(),Y=h.vec3();class q extends T{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,i){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=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const c=e.poi;if(o){if(o[3]<o[0]||o[4]<o[1]||o[5]<o[2])return;if(o[3]===o[0]&&o[4]===o[1]&&o[5]===o[2])return;o=o.slice();const t=h.getAABB3Center(o);this._look2=c||t;const i=h.subVec3(this._eye1,this._look1,X),s=h.normalizeVec3(i),r=c?h.getAABB3DiagPoint(o,c):h.getAABB3Diag(o),n=e.fitFOV||this._fitFOV,a=Math.abs(r/Math.tan(n*h.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*a,this._eye2[1]=this._look2[1]+s[1]*a,this._eye2[2]=this._look2[2]+s[2]*a,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(n||a||l)&&(this._flyingEyeLookUp=!!n&&!!a&&!!l,this._flyingEye=!!n&&!a,this._flyingLook=!!a&&!n,n&&(this._eye2[0]=n[0],this._eye2[1]=n[1],this._eye2[2]=n[2]),a&&(this._look2[0]=a[0],this._look2[1]=a[1],this._look2[2]=a[2]),l&&(this._up2[0]=l[0],this._up2[1]=l[1],this._up2[2]=l[2]));r?("ortho"===e.projection&&"ortho"!==s.projection&&(this._projection2="ortho",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.ortho.matrix.slice(),s.projection="customProjection"),"perspective"===e.projection&&"perspective"!==s.projection&&(this._projection2="perspective",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.perspective.matrix.slice(),s.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(Number.isFinite(e.duration)?1e3*e.duration:this._duration),this._flying=!0,M.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var i,s,r,o,n;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,o=e.look,n=e.up;else{let t=e;if((_.isNumeric(t)||_.isString(t))&&(s=t,t=this.scene.components[s],!t))return void this.error("Component not found: "+_.inQuotes(s));i=t.aabb||this.scene.aabb}const a=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var l=a?h.getAABB3DiagPoint(i,a):h.getAABB3Diag(i);let s;o=a||h.getAABB3Center(i,o),this._trail?h.subVec3(t.look,o,Y):h.subVec3(t.eye,t.look,Y),h.normalizeVec3(Y);s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(l/Math.tan((e.fitFOV||this._fitFOV)*h.DEGTORAD)):h.lenVec3(h.subVec3(t.eye,t.look,X)),h.mulVec3Scalar(Y,s),t.eye=h.addVec3(o,Y,X),t.look=o,this.scene.camera.ortho.scale=1.1*l}else(r||o||n)&&(r&&(t.eye=r),o&&(t.look=o),n&&(t.up=n));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 i=this.easing?q._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(h.subVec3(s.eye,s.look,Y),s.eye=h.lerpVec3(i,0,1,this._eye1,this._eye2,Z),s.look=h.subVec3(Z,Y,K)):this._flyingLook&&(s.look=h.lerpVec3(i,0,1,this._look1,this._look2,K),s.up=h.lerpVec3(i,0,1,this._up1,this._up2,J)):this._flyingEyeLookUp&&(s.eye=h.lerpVec3(i,0,1,this._eye1,this._eye2,Z),s.look=h.lerpVec3(i,0,1,this._look1,this._look2,K),s.up=h.lerpVec3(i,0,1,this._up1,this._up2,J)),this._projection2){const t="ortho"===this._projection2?q._easeOutExpo(e,0,1,1):q._easeInCubic(e,0,1,1);s.customProjection.matrix=h.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+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=Number.isFinite(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 $ extends T{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new q(this),this._t=0,this.state=$.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,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case $.SCRUBBING:return;case $.PLAYING:if(this._t+=this._playingRate*r,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=$.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case $.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=$.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(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=$.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=$.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=$.SCRUBBING,this._cameraFlightAnimation.flyTo(s,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=$.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=$.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=$.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}$.STOPPED=0,$.SCRUBBING=1,$.PLAYING=2,$.PLAYING_TO=3;class ee extends T{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}const te=new e({});class ie{constructor(e){this.id=te.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){te.removeItem(this.id)}}class se{constructor(e,t,i,s,r,o,n,a,l){switch(this._gl=e,this.type=t,this.allocated=!1,this.ConstructorType=i.constructor,i.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=o,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!n,this.stride=a||0,this.offset=l||0,this._allocate(i)}_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)))}getData(e=0,t=this.numItems-e){if(!this.allocated)return[];const i=new this.ConstructorType(t*this.itemSize);return this._gl.bindBuffer(this.type,this._handle),this._gl.getBufferSubData(this.type,e*this.itemByteSize*this.itemSize,i,0,t*this.itemSize),i}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)}}var re=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=h.vec3(),c=h.vec3(),u=h.vec3(),d=h.vec3(),p=h.vec3(),f=h.vec3(),m=h.vec3();return function(g,_,v,b){!function(r,o){const n={};let a,l,A,c;const h=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;u<d;u+=3)a=r[u],l=r[u+1],A=r[u+2],c=Math.round(a*h)+"_"+Math.round(l*h)+"_"+Math.round(A*h),void 0===n[c]&&(n[c]=p/3,e[p++]=a,e[p++]=l,e[p++]=A),t[u/3]=n[c];for(u=0,d=o.length;u<d;u++)s[u]=t[o[u]],i[s[u]]=o[u]}(g,_),function(t,i){o=0;for(let g=0,_=t;g<_;g+=3){const t=3*s[g],_=3*s[g+1],v=3*s[g+2];i?(n[0]=e[t],n[1]=e[t+1],n[2]=e[t+2],a[0]=e[_],a[1]=e[_+1],a[2]=e[_+2],l[0]=e[v],l[1]=e[v+1],l[2]=e[v+2],h.decompressPosition(n,i,A),h.decompressPosition(a,i,c),h.decompressPosition(l,i,u)):(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],u[0]=e[v],u[1]=e[v+1],u[2]=e[v+2]),h.subVec3(u,c,d),h.subVec3(A,c,p),h.cross3Vec3(d,p,f),h.normalizeVec3(f,m);const b=r[o]||(r[o]={normal:h.vec3()});b.normal[0]=m[0],b.normal[1]=m[1],b.normal[2]=m[2],o++}}(_.length,v);const y=[],w=Math.cos(h.DEGTORAD*b),B={};let x,P,C,M,F,E,I,T,D,S,R,U=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)x=s[e+i],P=s[e+(i+1)%3],C=Math.min(x,P),M=Math.max(x,P),F=C+","+M,void 0===B[F]?B[F]={index1:C,index2:M,face1:t,face2:void 0}:B[F].face2=t}for(F in B)E=B[F],void 0!==E.face2&&(I=r[E.face1].normal,T=r[E.face2].normal,D=h.dotVec3(I,T),D>w)||(S=i[E.index1],R=i[E.index2],(!U&&S>65535||R>65535)&&(U=!0),y.push(S),y.push(R));return U?new Uint32Array(y):new Uint16Array(y)}}();const oe=function(){const e=h.mat4(),t=h.mat4();return function(i,s){s=s||h.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,c=65535;return h.identityMat4(e),h.translationMat4v(i,e),h.identityMat4(t),h.scalingMat4v([a/c,l/c,A/c],t),h.mulMat4(e,t,s),s}}();var ne=function(){const e=h.mat4(),t=h.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a<i.length;a+=3)o[a+0]=Math.max(0,Math.min(65535,Math.floor((i[a+0]-s[0])*n[0]))),o[a+1]=Math.max(0,Math.min(65535,Math.floor((i[a+1]-s[1])*n[1]))),o[a+2]=Math.max(0,Math.min(65535,Math.floor((i[a+2]-s[2])*n[2])));h.identityMat4(e),h.translationMat4v(s,e),h.identityMat4(t),h.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t);return{quantized:o,decodeMatrix:h.mulMat4(e,t,h.identityMat4())}}}();var ae=function(){const e=h.mat3(),t=h.mat3();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let a;for(a=0;a<i.length;a+=2)o[a+0]=Math.max(0,Math.min(65535,Math.floor((i[a+0]-s[0])*n[0]))),o[a+1]=Math.max(0,Math.min(65535,Math.floor((i[a+1]-s[1])*n[1])));h.identityMat3(e),h.translationMat3v(s,e),h.identityMat3(t),h.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t);return{quantized:o,decodeMatrix:h.mulMat3(e,t,h.identityMat3())}}}();function le(e,t,i,s){let r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),o=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(o))*(r>=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Ae(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function ce(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const he={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=3)for(r=0;r<3;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},createPositionsDecodeMatrix:oe,compressPositions:ne,compressPosition:function(e,t,i){const s=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]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*s[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*s[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*s[2])))},decompressPositions:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t,i=e){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){const t=new Float32Array(2),i=new Float32Array(2);let s,r;for(s=0;s<2;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=2)for(r=0;r<2;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},compressUVs:ae,decompressUVs:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let i,s,r,o,n;for(let a=0;a<e.length;a+=3)r=i=le(e,a,"floor","floor"),s=Ae(i),o=n=ce(e,a,s),i=le(e,a,"ceil","floor"),s=Ae(i),o=ce(e,a,s),o>n&&(r=i,n=o),i=le(e,a,"floor","ceil"),s=Ae(i),o=ce(e,a,s),o>n&&(r=i,n=o),i=le(e,a,"ceil","ceil"),s=Ae(i),o=ce(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const n=1-Math.abs(r)-Math.abs(o);n<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},ue=p.memory,de=h.AABB3();class pe extends ee{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new ie({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 i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.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'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=he.getPositionsBounds(t.positions),s=he.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=he.getUVBounds(t.uv),s=he.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=he.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.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(),ue.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),ue.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new se(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),ue.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new se(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),ue.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new se(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),ue.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new se(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),ue.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,i=re(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),ue.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=h.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new se(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new se(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),ue.positions+=this._pickTrianglePositionsBuf.numItems,ue.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),he.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=he.getPositionsBounds(e),s=he.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),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),he.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,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),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),he.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,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),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,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),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,de,this._state.positionsDecodeMatrix),h.AABB3ToOBB3(de,this._obb),this._obbDirty=!1),this._obb}_getMetrics(){if(!("_metrics"in this))switch(this._state.primitiveName){case"solid":case"surface":case"triangles":{const e=this._state.indices,t=this._state.positions,i=(i,s)=>{const r=3*e[i];for(let e=0;e<3;++e)s[e]=t[r+e];return s},s=[h.vec3(),h.vec3(),h.vec3(),h.vec3()];let r=0;const o=h.vec3([0,0,0]);for(let t=0;t<e.length;t+=3){const e=i(t,s[0]),n=i(t+1,s[1]),a=i(t+2,s[2]);h.addVec3(e,n,s[3]),h.addVec3(a,s[3],s[3]);const l=h.lenVec3(h.cross3Vec3(h.subVec3(n,e,s[1]),h.subVec3(a,e,s[2]),s[0]))/2;r+=l,h.mulVec3Scalar(s[3],l,s[3]),h.addVec3(o,s[3],o)}this._metrics={surfaceArea:r,centroid:h.mulVec3Scalar(o,1/r/3,o)};break}default:this._metrics={surfaceArea:0}}return this._metrics}get surfaceArea(){return this._getMetrics().surfaceArea}get centroid(){return this._getMetrics().centroid}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(),ue.meshes--}}const fe=p.memory,me=h.AABB3();class ge extends ee{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new ie({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 i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.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'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=he.getPositionsBounds(t.positions),o=he.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new se(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),fe.positions+=i.positionsBuf.numItems,h.positions3ToAABB3(t.positions,this._aabb),h.positions3ToAABB3(r,me,i.positionsDecodeMatrix),h.AABB3ToOBB3(me,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new se(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),fe.colors+=i.colorsBuf.numItems}if(t.uv){const e=he.getUVBounds(t.uv),r=he.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new se(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),fe.uvs+=i.uvBuf.numItems}if(t.normals){const e=he.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new se(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),fe.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),fe.indices+=i.indicesBuf.numItems;const o=re(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),fe.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(),fe.meshes--}}var _e={};function ve(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,c=-s+a,h=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[h,u,d,l,u,d,l,A,d,h,A,d,h,u,d,h,A,d,h,A,c,h,u,c,h,u,d,h,u,c,l,u,c,l,u,d,l,u,d,l,u,c,l,A,c,l,A,d,l,A,c,h,A,c,h,A,d,l,A,d,h,A,c,l,A,c,l,u,c,h,u,c],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]})}function be(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,c=-s+a,h=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,c,l,A,d,l,u,c,l,u,d,h,A,c,h,A,d,h,u,c,h,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function ye(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,c=a?a[2]:0,h=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,m=[],g=[],v=[],b=[];let y,w,B,x,P,C,M,F,E,I,T;const D=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=h-y*u,w=0;w<=r;w++)B=Math.sin(w*d),x=Math.cos(w*d),g.push(P*B),g.push(D),g.push(P*x),v.push(w*p),v.push(1*y/o),m.push(P*B+l),m.push(C+A),m.push(P*x+c);for(y=0;y<o;y++)for(w=0;w<=r;w++)M=y*(r+1)+w,F=M+r,b.push(M),b.push(F),b.push(F+1),b.push(M),b.push(F+1),b.push(M+1);if(!n&&t>0){for(E=m.length/3,g.push(0),g.push(1),g.push(0),v.push(.5),v.push(.5),m.push(0+l),m.push(h+A),m.push(0+c),w=0;w<=r;w++)B=Math.sin(w*d),x=Math.cos(w*d),I=.5*Math.sin(w*d)+.5,T=.5*Math.cos(w*d)+.5,g.push(t*B),g.push(1),g.push(t*x),v.push(I),v.push(T),m.push(t*B+l),m.push(h+A),m.push(t*x+c);for(w=0;w<r;w++)a=E,M=E+1+w,b.push(M),b.push(M+1),b.push(a)}if(!n&&i>0){for(E=m.length/3,g.push(0),g.push(-1),g.push(0),v.push(.5),v.push(.5),m.push(0+l),m.push(0-h+A),m.push(0+c),w=0;w<=r;w++)B=Math.sin(w*d),x=Math.cos(w*d),I=.5*Math.sin(w*d)+.5,T=.5*Math.cos(w*d)+.5,g.push(i*B),g.push(-1),g.push(i*x),v.push(I),v.push(T),m.push(i*B+l),m.push(0-h+A),m.push(i*x+c);for(w=0;w<r;w++)a=E,M=E+1+w,b.push(a),b.push(M+1),b.push(M)}return _.apply(e,{positions:m,normals:g,uv:v,indices:b})}function we(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Be(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,c=i/2,h=Math.floor(s)||1,u=Math.floor(r)||1,d=h+1,p=u+1,f=t/h,m=i/u,g=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,w,B,x,P,C,M,F=0,E=0;for(y=0;y<p;y++){const e=y*m-c;for(w=0;w<d;w++)B=w*f-A,g[F]=B+n,g[F+1]=a,g[F+2]=-e+l,v[F+1]=1,b[E]=w/h,b[E+1]=(u-y)/u,F+=3,E+=2}F=0;const I=new(g.length/3>65535?Uint32Array:Uint16Array)(h*u*6);for(y=0;y<u;y++)for(w=0;w<h;w++)x=w+d*y,P=w+d*(y+1),C=w+1+d*(y+1),M=w+1+d*y,I[F]=M,I[F+1]=P,I[F+2]=x,I[F+3]=M,I[F+4]=C,I[F+5]=P,F+=6;return _.apply(e,{positions:g,normals:v,uv:b,indices:I})}function xe(e={}){const t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0;let o=e.radius||1;o<0&&(console.error("negative radius not allowed - will invert"),o*=-1);let n=e.heightSegments||18;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n=Math.floor(t*n),n<18&&(n=18);let a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),a=Math.floor(t*a),a<18&&(a=18);const l=[],A=[],c=[],h=[];let u,d,p,f,m,g,v,b,y,w,B,x,P,C,M;for(u=0;u<=n;u++)for(p=u*Math.PI/n,f=Math.sin(p),m=Math.cos(p),d=0;d<=a;d++)g=2*d*Math.PI/a,v=Math.sin(g),b=Math.cos(g),y=b*f,w=m,B=v*f,x=1-d/a,P=u/n,A.push(y),A.push(w),A.push(B),c.push(x),c.push(P),l.push(i+o*y),l.push(s+o*w),l.push(r+o*B);for(u=0;u<n;u++)for(d=0;d<a;d++)C=u*(a+1)+d,M=C+a+1,h.push(C+1),h.push(M+1),h.push(M),h.push(C+1),h.push(M),h.push(C);return _.apply(e,{positions:l,normals:A,uv:c,indices:h})}function Pe(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);let s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);let r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);let o=e.arc||2*Math.PI;o<0&&(console.warn("negative arc not allowed - will invert"),o*=-1),o>360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,c=[],u=[],d=[],p=[];let f,m,g,v,b,y,w,B,x,P,C,M;for(B=0;B<=r;B++)for(w=0;w<=s;w++)f=w/s*o,m=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),g=(t+i*Math.cos(m))*Math.cos(f),v=(t+i*Math.cos(m))*Math.sin(f),b=i*Math.sin(m),c.push(g+a),c.push(v+l),c.push(b+A),d.push(1-w/s),d.push(B/r),y=h.normalizeVec3(h.subVec3([g,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(B=1;B<=r;B++)for(w=1;w<=s;w++)x=(s+1)*B+w-1,P=(s+1)*(B-1)+w-1,C=(s+1)*(B-1)+w,M=(s+1)*B+w,p.push(x),p.push(P),p.push(C),p.push(C),p.push(M),p.push(x);return _.apply(e,{positions:c,normals:u,uv:d,indices:p})}_e.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},_e.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(_e.parse._buffToStr(e));window.location.href=i},_e.clone=function(e){return JSON.parse(JSON.stringify(e))},_e.bin={},_e.bin.f=new Float32Array(1),_e.bin.fb=new Uint8Array(_e.bin.f.buffer),_e.bin.rf=function(e,t){for(var i=_e.bin.f,s=_e.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},_e.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},_e.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},_e.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},_e.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},_e.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},_e.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},_e.parse={},_e.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;s<t.length;s++)i=i.concat(String.fromCharCode(t[s]));return i},_e.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),i=new Uint8Array(t),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return t},_e.parse._readLine=function(e,t){for(var i="";10!=e[t];)i+=String.fromCharCode(e[t++]);return i},_e.parse.fromJSON=function(e){return JSON.parse(_e.parse._buffToStr(e))},_e.parse.toJSON=function(e){var t=JSON.stringify(e);return _e.parse._strToBuff(t)},_e.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},i={from:0,to:0},s=0,r=new Uint8Array(e);s<r.length;){var o=_e.parse._readLine(r,s);s+=o.length+1;var n=(o=(o=o.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==n[0]&&(i.to=t.i_verts.length,null==t.groups[n[1]]&&(t.groups[n[1]]={from:t.i_verts.length,to:0}),i=t.groups[n[1]]),"v"==n[0]){var a=parseFloat(n[1]),l=parseFloat(n[2]),A=parseFloat(n[3]);t.c_verts.push(a,l,A)}if("vt"==n[0]){a=parseFloat(n[1]),l=1-parseFloat(n[2]);t.c_uvt.push(a,l)}if("vn"==n[0]){a=parseFloat(n[1]),l=parseFloat(n[2]),A=parseFloat(n[3]);t.c_norms.push(a,l,A)}if("f"==n[0]){var c=n[1].split("/"),h=n[2].split("/"),u=n[3].split("/"),d=parseInt(c[0])-1,p=parseInt(h[0])-1,f=parseInt(u[0])-1,m=parseInt(c[1])-1,g=parseInt(h[1])-1,_=parseInt(u[1])-1,v=parseInt(c[2])-1,b=parseInt(h[2])-1,y=parseInt(u[2])-1,w=t.c_verts.length/3,B=t.c_uvt.length/2,x=t.c_norms.length/3;if(d<0&&(d=w+d+1),p<0&&(p=w+p+1),f<0&&(f=w+f+1),m<0&&(m=B+m+1),g<0&&(g=B+g+1),_<0&&(_=B+_+1),v<0&&(v=x+v+1),b<0&&(b=x+b+1),y<0&&(y=x+y+1),t.i_verts.push(d,p,f),t.i_uvt.push(m,g,_),t.i_norms.push(v,b,y),5==n.length){var P=n[4].split("/"),C=parseInt(P[0])-1,M=parseInt(P[1])-1,F=parseInt(P[2])-1;C<0&&(C=w+C+1),M<0&&(M=B+M+1),F<0&&(F=x+F+1),t.i_verts.push(d,f,C),t.i_uvt.push(m,_,M),t.i_norms.push(v,y,F)}}}return i.to=t.i_verts.length,t},_e.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},i={};i.ident=_e.bin.ril(e,0),i.version=_e.bin.ril(e,4),i.skinwidth=_e.bin.ril(e,8),i.skinheight=_e.bin.ril(e,12),i.framesize=_e.bin.ril(e,16),i.num_skins=_e.bin.ril(e,20),i.num_vertices=_e.bin.ril(e,24),i.num_st=_e.bin.ril(e,28),i.num_tris=_e.bin.ril(e,32),i.num_glcmds=_e.bin.ril(e,36),i.num_frames=_e.bin.ril(e,40),i.offset_skins=_e.bin.ril(e,44),i.offset_st=_e.bin.ril(e,48),i.offset_tris=_e.bin.ril(e,52),i.offset_frames=_e.bin.ril(e,56),i.offset_glcmds=_e.bin.ril(e,60),i.offset_end=_e.bin.ril(e,64);var s=i.offset_st;t.c_uvt=[];for(var r=0;r<i.num_st;r++){var o=_e.bin.rsl(e,s)/i.skinwidth,n=_e.bin.rsl(e,s+2)/i.skinheight;t.c_uvt.push(o,n),s+=4}s=i.offset_tris;var a=[],l=[];t.i_verts=a,t.i_uvt=l;for(r=0;r<i.num_tris;r++)a.push(_e.bin.rsl(e,s),_e.bin.rsl(e,s+2),_e.bin.rsl(e,s+4)),l.push(_e.bin.rsl(e,s+6),_e.bin.rsl(e,s+8),_e.bin.rsl(e,s+10)),s+=12;s=i.offset_skins;t.skins=[];for(r=0;r<i.num_skins;r++)t.skins.push(_e.bin.rASCII0(e,s)),s+=64;s=i.offset_frames;t.frames=[];var A=_e.parse.fromMD2._normals;for(r=0;r<i.num_frames;r++){var c={},h=_e.bin.rf(e,s),u=_e.bin.rf(e,s+4),d=_e.bin.rf(e,s+8);s+=12;var p=_e.bin.rf(e,s),f=_e.bin.rf(e,s+4),m=_e.bin.rf(e,s+8);s+=12,c.name=_e.bin.rASCII0(e,s),s+=16,c.verts=[],c.norms=[];for(var g=0;g<i.num_vertices;g++)c.verts.push(e[s]*h+p,e[s+1]*u+f,e[s+2]*d+m),c.norms.push(A[3*e[s+3]],A[3*e[s+3]+1],A[3*e[s+3]+2]),s+=4;t.frames.push(c)}return t},_e.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],_e.parse.fromCollada=function(e){var t=_e.parse._buffToStr(e),i=(new DOMParser).parseFromString(t,"text/xml"),s={},r=(i=i.childNodes[0]).getElementsByTagName("asset")[0],o=i.getElementsByTagName("library_geometries")[0],n=i.getElementsByTagName("library_images")[0],a=i.getElementsByTagName("library_materials")[0],l=i.getElementsByTagName("library_effects")[0];return r&&(s.asset=_e.parse.fromCollada._asset(r)),o&&(s.geometries=_e.parse.fromCollada._libGeometries(o)),n&&(s.images=_e.parse.fromCollada._libImages(n)),a&&(s.materials=_e.parse.fromCollada._libMaterials(a)),l&&(s.effects=_e.parse.fromCollada._libEffects(l)),s},_e.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}},_e.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],i=0;i<e.length;i++){var s=e[i],r=_e.parse.fromCollada._getMesh(s.getElementsByTagName("mesh")[0]);t.push(r)}return t},_e.parse.fromCollada._getMesh=function(e){for(var t={},i=e.getElementsByTagName("source"),s=t.sources={},r=0;r<i.length;r++){for(var o=i[r].getElementsByTagName("float_array")[0].textContent.split(" "),n=o.length-(""==o[o.length-1]?1:0),a=new Array(n),l=0;l<n;l++)a[l]=parseFloat(o[l]);s[i[r].getAttribute("id")]=a}t.triangles=[];var A=e.getElementsByTagName("triangles");if(null==A)return t;for(r=0;r<A.length;r++){var c={},h=A[r];c.material=h.getAttribute("material");var u=h.getElementsByTagName("input"),d=[];for(l=0;l<u.length;l++){var p=u[l];a=[];d[parseInt(p.getAttribute("offset"))]=a;var f=p.getAttribute("semantic");c["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):p.getAttribute("source").substring(1),c["i_"+f]=a,s[c["s_"+f]]}var m=h.getElementsByTagName("p")[0].textContent.split(" "),g=3*Math.floor(m.length/3);for(l=0;l<g;l++)d[l%u.length].push(parseInt(m[l]));t.triangles.push(c)}return t},_e.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("id")]=e[i].getElementsByTagName("init_from")[0].textContent;return t},_e.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("name")]=e[i].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},_e.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},i=0;i<e.length;i++){for(var s={},r=e[i].getElementsByTagName("newparam"),o=0;o<r.length;o++){var n=r[o].getElementsByTagName("surface")[0];n&&(s.surface=n.getElementsByTagName("init_from")[0].textContent)}t[e[i].getAttribute("id")]=s}return t},_e.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=_e.bin.rsl(e,0))return null;for(var i=_e.bin.ril(e,2),s=6;s<i;){var r=_e.bin.rsl(e,s),o=_e.bin.ril(e,s+2);15677==r&&(t.edit=_e.parse.from3DS._edit3ds(e,s,o)),45056==r&&(t.keyf=_e.parse.from3DS._keyf3ds(e,s,o)),s+=o}return t},_e.parse.from3DS._edit3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);16384==o&&(null==s.objects&&(s.objects=[]),s.objects.push(_e.parse.from3DS._edit_object(e,r,n))),r+=n}return s},_e.parse.from3DS._keyf3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);45058==o&&(null==s.desc&&(s.desc=[]),s.desc.push(_e.parse.from3DS._keyf_objdes(e,r,n))),r+=n}return s},_e.parse.from3DS._keyf_objdes=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);45072==o&&(s.hierarchy=_e.parse.from3DS._keyf_objhierarch(e,r,n)),45073==o&&(s.dummy_name=_e.bin.rASCII0(e,r+6)),r+=n}return s},_e.parse.from3DS._keyf_objhierarch=function(e,t,i){var s={},r=t+6;return s.name=_e.bin.rASCII0(e,r),r+=s.name.length+1,s.hierarchy=_e.bin.rsl(e,r+4),s},_e.parse.from3DS._edit_object=function(e,t,i){var s={},r=t+6;for(s.name=_e.bin.rASCII0(e,r),r+=s.name.length+1;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);16640==o&&(s.mesh=_e.parse.from3DS._obj_trimesh(e,r,n)),r+=n}return s},_e.parse.from3DS._obj_trimesh=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=_e.bin.rsl(e,r),n=_e.bin.ril(e,r+2);16656==o&&(s.vertices=_e.parse.from3DS._tri_vertexl(e,r,n)),16672==o&&(s.indices=_e.parse.from3DS._tri_facel1(e,r,n)),16704==o&&(s.uvt=_e.parse.from3DS._tri_mappingcoors(e,r,n)),16736==o&&(s.local=_e.parse.from3DS._tri_local(e,r,n)),r+=n}return s},_e.parse.from3DS._tri_vertexl=function(e,t,i){var s=[],r=t+6,o=_e.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)s.push(_e.bin.rf(e,r)),s.push(_e.bin.rf(e,r+4)),s.push(_e.bin.rf(e,r+8)),r+=12;return s},_e.parse.from3DS._tri_facel1=function(e,t,i){var s=[],r=t+6,o=_e.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)s.push(_e.bin.rsl(e,r)),s.push(_e.bin.rsl(e,r+2)),s.push(_e.bin.rsl(e,r+4)),r+=8;return s},_e.parse.from3DS._tri_mappingcoors=function(e,t,i){var s=[],r=t+6,o=_e.bin.rsl(e,r);r+=2;for(var n=0;n<o;n++)s.push(_e.bin.rf(e,r)),s.push(1-_e.bin.rf(e,r+4)),r+=8;return s},_e.parse.from3DS._tri_local=function(e,t,i){var s={},r=t+6;return s.X=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s.Y=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s.Z=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s.C=[_e.bin.rf(e,r),_e.bin.rf(e,r+4),_e.bin.rf(e,r+8)],r+=12,s},_e.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},i={};return i.id=_e.bin.ril(e,0),i.verS=_e.bin.ril(e,4),i.texS=_e.bin.ril(e,8),i.indS=_e.bin.ril(e,12),i.verO=_e.bin.ril(e,16),i.verL=_e.bin.ril(e,20),i.texO=_e.bin.ril(e,24),i.texL=_e.bin.ril(e,28),i.indO=_e.bin.ril(e,32),i.indL=_e.bin.ril(e,36),0!=i.verO&&(t.vertices=_e.parse.fromBIV._readFloats(e,i.verO,i.verL)),0!=i.texO&&(t.uvt=_e.parse.fromBIV._readFloats(e,i.texO,i.texL)),0!=i.indO&&(t.indices=_e.parse.fromBIV._readInts(e,i.indO,i.indL,i.indS)),t},_e.parse.toBIV=function(e){for(var t=0,i=0;i<e.indices.length;i++)t=Math.max(t,e.indices[i]);var s=32;t<=65535&&(s=16);var r=40;e.vertices&&(r+=4*e.vertices.length),e.uvt&&(r+=4*e.uvt.length),e.indices&&(r+=e.indices.length*s/8);var o=new Uint8Array(r);_e.bin.wil(o,0,1769365870),_e.bin.wil(o,4,32),_e.bin.wil(o,8,32),_e.bin.wil(o,12,s);var n=40;return e.vertices&&(_e.bin.wil(o,16,n),_e.bin.wil(o,20,4*e.vertices.length),_e.parse.fromBIV._writeFloats(o,n,e.vertices),n+=4*e.vertices.length),e.uvt&&(_e.bin.wil(o,24,n),_e.bin.wil(o,28,4*e.uvt.length),_e.parse.fromBIV._writeFloats(o,n,e.uvt),n+=4*e.uvt.length),e.indices&&(_e.bin.wil(o,32,n),_e.bin.wil(o,36,4*e.indices.length),_e.parse.fromBIV._writeInts(o,n,e.indices,s)),o.buffer},_e.parse.fromBIV._readFloats=function(e,t,i){for(var s=[],r=0;r<i/4;r++)s.push(_e.bin.rf(e,t+4*r));return s},_e.parse.fromBIV._writeFloats=function(e,t,i){for(var s=0;s<i.length;s++)_e.bin.wf(e,t+4*s,i[s])},_e.parse.fromBIV._readInts=function(e,t,i,s){for(var r=[],o=0;o<i/4;o++)16==s&&r.push(_e.bin.rsl(e,t+2*o)),32==s&&r.push(_e.bin.ril(e,t+4*o));return r},_e.parse.fromBIV._writeInts=function(e,t,i,s){for(var r=0;r<i.length;r++)16==s&&_e.bin.wsl(e,t+2*r,i[r]),32==s&&_e.bin.wil(e,t+4*r,i[r])},_e.gen={},_e.gen.Plane=function(e,t,i,s){i||(i=1),s||(s=1);for(var r={verts:[],inds:[],uvt:[]},o=e+1,n=t+1,a=0;a<n;a++)for(var l=0;l<o;l++){var A=l*(2/e)-1,c=a*(2/t)-1;r.verts.push(A,c,0),r.uvt.push(i*l/e,s*a/t),a<t&&l<e&&r.inds.push(a*o+l,a*o+l+1,(a+1)*o+l,a*o+l+1,(a+1)*o+l,(a+1)*o+l+1)}return r},_e.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]}},_e.gen.Sphere=function(e,t){for(var i={verts:[],inds:[],uvt:[]},s=e+1,r=t+1,o=0;o<r;o++)for(var n=0;n<s;n++){var a=-Math.PI/2+o*Math.PI/t,l=2*n*Math.PI/e,A=Math.cos(a)*Math.cos(l),c=Math.sin(a),h=Math.cos(a)*Math.sin(l);i.verts.push(A,c,h),i.uvt.push(n/e,o/t),o<t&&n<e&&i.inds.push(s*o+n,s*o+n+1,s*(o+1)+n,s*o+n+1,s*(o+1)+n,s*(o+1)+n+1)}return i},_e.mat={},_e.mat.scale=function(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]},_e.mat.translate=function(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]},_e.mat.rotateDeg=function(e,t,i){var s=Math.PI/180;return _e.mat.rotate(e*s,t*s,i*s)},_e.mat.rotate=function(e,t,i){var s=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],r=e,o=t,n=i,a=Math.cos(r),l=Math.cos(o),A=Math.cos(n),c=Math.sin(r),h=Math.sin(o),u=Math.sin(n);return s[0]=l*A,s[1]=-l*u,s[2]=h,s[4]=a*u+c*h*A,s[5]=a*A-c*h*u,s[6]=-c*l,s[8]=c*u-a*h*A,s[9]=c*A+a*h*u,s[10]=a*l,s},_e.edit={},_e.edit.interpolate=function(e,t,i,s){for(var r=0;r<e.length;r++)i[r]=e[r]+s*(t[r]-e[r])},_e.edit.transform=function(e,t){for(var i=0;i<e.length;i+=3){var s=e[i],r=e[i+1],o=e[i+2];e[i+0]=t[0]*s+t[4]*r+t[8]*o+t[12],e[i+1]=t[1]*s+t[5]*r+t[9]*o+t[13],e[i+2]=t[2]*s+t[6]*r+t[10]*o+t[14]}},_e.edit.unwrap=function(e,t,i){for(var s=new Array(Math.floor(e.length/3)*i),r=0;r<e.length;r++)for(var o=0;o<i;o++)s[r*i+o]=t[e[r]*i+o];return s},_e.edit.remap=function(e,t,i,s){for(var r=new Array(i.length),o=0;o<e.length;o++)for(var n=0;n<s;n++)r[t[o]*s+n]=i[e[o]*s+n];return r},_e.utils={},_e.utils.getAABB=function(e){var t,i,s,r,o,n;r=o=n=-(t=i=s=999999999);for(var a=0;a<e.length;a+=3){var l=e[a+0],A=e[a+1],c=e[a+2];l<t&&(t=l),l>r&&(r=l),A<i&&(i=A),A>o&&(o=A),c<s&&(s=c),A>n&&(n=c)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};const Ce={" ":{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 Me(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,c,h,u,d,p,f,m,g,v=(l||"").split("\n"),b=0,y=0,w=.04,B=0;B<v.length;B++){A=0,h=(c=v[B]).length;for(var x=0;x<h;x++)if(u=Ce[c.charAt(x)]){d=1,p=-1,f=-1,m=u.points.length;for(var P=0;P<m;P++)-1!==(g=u.points[P])[0]||-1!==g[1]?(n.push(A+g[0]*o*w+i),n.push(y+g[1]*o*w+s),n.push(0+r),-1===p?p=b:(-1===f||(p=f),f=b),b++,d?d=!1:(a.push(p),a.push(f))):d=1;A+=u.width*w*o}y-=35*w*o}return _.apply(e,{primitive:"lines",positions:n,indices:a})}function Fe(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e<t-1;e++)i.push(e),i.push(e+1);return _.apply(e,{primitive:"lines",positions:e.points,indices:i})}function Ee(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],o=e.startPoint[2],n=e.endPoint[0],a=e.endPoint[1],l=e.endPoint[2],A=Math.sqrt((n-s)**2+(a-r)**2+(l-o)**2),c=[(n-s)/A,(a-r)/A,(l-o)/A];if(e.pattern){let h=e.pattern.length,u=!1,d=0,p=0,f=0,m=[s,r,o],g=e.pattern[p];for(i.push(m[0],m[1],m[2]);g<=A-d;){let s=[c[0]*g,c[1]*g,c[2]*g],r=[m[0]+s[0],m[1]+s[1],m[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(f),t.push(f+1)),u=!u,f+=1,m=r,p+=1,p>=h&&(p=0),d+=g,g=e.pattern[p]}e.extendToEnd&&(i.push(n,a,l),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,o,n,a,l);return _.apply(e,{primitive:"lines",positions:i,indices:t})}const Ie=h.vec4(4),Te=h.vec4(),De=h.vec4(),Se=h.vec3([1,0,0]),Re=h.vec3([0,1,0]),Ue=h.vec3([0,0,1]),Le=h.vec3(3),ke=h.vec3(3),Oe=h.identityMat4();class Ne extends T{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 i=0,s=e.length;i<s;i++)this.addChild(e[i],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,i=this._children.length;t<i;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,i=this._children.length;t<i;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,i=this._children.length;t<i;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,i=this._children.length;t<i;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,i=this._children.length;t<i;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,i=this._children.length;t<i;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._children.length;t<i;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,i=this._children.length;e<i;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,i=this._children.length;t<i;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,i=this._children.length;t<i;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,i=this._children.length;t<i;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,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,i=e._children.length;t<i;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,i=this._children.length;t<i;t++)e=this._children[t],e.collidable&&h.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(_.isNumeric(e)||_.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+_.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,i=this._children.length;t<i;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,i=this._children.length;t<i;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(_.isNumeric(e)||_.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+_.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||Oe),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 Ie[0]=e[0],Ie[1]=e[1],Ie[2]=e[2],Ie[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ie,Te),h.mulQuaternions(this.quaternion,Te,De),this.quaternion=De,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ie[0]=e[0],Ie[1]=e[1],Ie[2]=e[2],Ie[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Ie,Te),h.mulQuaternions(Te,this.quaternion,Te),this}rotateX(e){return this.rotate(Se,e)}rotateY(e){return this.rotate(Re,e)}rotateZ(e){return this.rotate(Ue,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Le),h.mulVec3Scalar(Le,t,ke),h.addVec3(this.position,ke,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Se,e)}translateY(e){return this.translate(Re,e)}translateZ(e){return this.translate(Ue,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(0);let t;for(let i=0,s=e.length;i<s;i++)t=e[i],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}const Ve=h.vec3(),Qe=h.vec4(),He=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,h.transformVec4(s,t,i),h.setMat4Translation(s,i,o),o.slice()}}();function Ge(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function je(e,t,i,s=1e3){const r=h.getPositionsCenter(e,Ve),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i<s;i+=3)t[i+0]=e[i+0]-o,t[i+1]=e[i+1]-n,t[i+2]=e[i+2]-a;return l}function ze(e,t,i,s,r){const o=r?(Qe.set(i,0),Qe[3]=1,h.mulMat4v4(r,Qe,Qe)):i,n=h.dotVec3(t,o)+e,a=h.normalizeVec3(t,Ve);return h.mulVec3Scalar(a,-n,s),s}const We=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),A.push("uniform vec3 scale;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.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&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");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+";")))}l&&(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 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = scale[0];"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = scale[1];"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(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;"),r.normalsBuf)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((viewMatrix2 * 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((viewMatrix2 * 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((viewMatrix2 * 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);")}}A.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),a&&A.push("vWorldPosition = worldPosition;");"points"===r.primitiveName&&A.push("gl_PointSize = pointSize;");A.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(A.push("vFragDepth = 1.0 + clipPos.w;"),A.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return A.push("gl_Position = clipPos;"),A.push("}"),A}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState;e._material._state;const s=e._geometry._state,r=i.getNumAllocatedSectionPlanes()>0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian 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"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}n.push("in vec4 vColor;"),o&&(n.push("uniform float gammaFactor;"),n.push(" vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push("if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;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("}")}"points"===s.primitiveName&&(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("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,c=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=Ze(e),u=s.getNumAllocatedSectionPlanes()>0,d=Ke(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&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;"),f.push("uniform vec3 scale;"),u&&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;"));o.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=o.lights.length;e<t;e++)n=o.lights[e],"ambient"!==n.type&&("dir"===n.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===n.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===n.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===n.type&&"view"===n.space||f.push("out vec4 vViewLightReverseDirAndDist"+e+";"));p&&(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("}"))}c&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = scale[0];"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = scale[1];"),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(d){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=o.lights.length;e<t;e++)o.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;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");h&&(p?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;"),A?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(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; "),o.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=o.lights.length;e<t;e++)n=o.lights[e],"ambient"!==n.type&&("dir"===n.type&&"world"===n.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===n.type&&("world"===n.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);")))}c&&(p?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;"));r.colors&&f.push("vColor = color;");"points"===r.primitiveName&&f.push("gl_PointSize = pointSize;");u&&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));"));l&&f.push("clipPos.z = clipPos.w;");if(f.push("gl_Position = clipPos;"),d){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=o.lights.length;e<t;e++)o.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 i=e._material,s=e._geometry._state,r=e.scene._sectionPlanesState,o=e.scene._lightsState,n=e._material._state,a=r.getNumAllocatedSectionPlanes()>0,l=Ze(e),A=s.uvBuf,c="PhongMaterial"===n.type,h="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=Ke(e);t.gammaInput;const p=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;"));d&&(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("}"),p&&(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(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var m=0;m<r.getNumAllocatedSectionPlanes();m++)f.push("uniform bool sectionPlaneActive"+m+";"),f.push("uniform vec3 sectionPlanePos"+m+";"),f.push("uniform vec3 sectionPlaneDir"+m+";")}l&&(o.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.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("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Xe[o.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;")),o.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||u)&&(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("}"),o.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 = "+Xe[o.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("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.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;")),o.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;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._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("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._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("}"),i._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;")),i._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;")),i._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;")),i._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;")),i._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;"),l)for(let e=0,t=o.lights.length;e<t;e++){const t=o.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(d)for(let e=0,t=o.lights.length;e<t;e++)o.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) {"),a){f.push("if (clippable) {"),f.push(" float dist = 0.0;");for(m=0;m<r.getNumAllocatedSectionPlanes();m++)f.push("if (sectionPlaneActive"+m+") {"),f.push(" dist += clamp(dot(-sectionPlaneDir"+m+".xyz, vWorldPosition.xyz - sectionPlanePos"+m+".xyz), 0.0, 1000.0);"),f.push("}");f.push(" if (dist > 0.0) { discard; }"),f.push("}")}"points"===s.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;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._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 = "+Xe[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Xe[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Xe[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Xe[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._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);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._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;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._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);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._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;"),c&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(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;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||h)&&(o.lightMaps.length>0||o.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=o.lights.length;e<t;e++){const t=o.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);"),d&&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;"),c&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(u||h)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}c?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;"),p&&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))},Xe={};function Ke(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,i=t.length;e<i;e++)if(t[e].castsShadow)return!0;return!1}function Ze(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}Xe[3e3]="linearToLinear",Xe[3001]="sRGBToLinear";class Je{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e<t.length;e++)s.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(s.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class Ye{constructor(e,t){this.bindTexture=function(i,s){return!!i.bind(s)&&(e.uniform1i(t,s),!0)}}}class qe{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 $e=new e({});function et(e){const t=[];let i,s;for(let r=0,o=e.length;r<o;r++)i=e[r],s=i.indexOf("/"),s>0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function tt(e){console.error(e.join("\n"))}class it{constructor(e,t){this.id=$e.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 Je(e,e.VERTEX_SHADER,et(this.source.vertex)),this._fragmentShader=new Je(e,e.FRAGMENT_SHADER,et(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void tt(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void tt(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void tt(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void tt(this.errors);let t,i,s,r,o;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 tt(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<n;++i)s=e.getActiveUniform(this.handle,i),s&&(r=s.name,"\0"===r[r.length-1]&&(r=r.substr(0,r.length-1)),o=e.getUniformLocation(this.handle,r),s.type===e.SAMPLER_2D||s.type===e.SAMPLER_CUBE||35682===s.type||e instanceof WebGL2RenderingContext&&(s.type===e.UNSIGNED_INT_SAMPLER_2D||s.type===e.INT_SAMPLER_2D)?this.samplers[r]=new Ye(e,o):this.uniforms[r]=o);const a=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<a;i++)t=e.getActiveAttrib(this.handle,i),t&&(o=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new qe(e,o));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,i){if(!this.allocated)return!1;const s=this.samplers[e];return!!s&&s.bindTexture(t,i)}destroy(){this.allocated&&($e.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)}}const st={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},rt=document.createElement("canvas");if(rt){const e=rt.getContext("webgl",{antialias:!0})||rt.getContext("experimental-webgl",{antialias:!0});st.WEBGL=!!e,st.WEBGL&&(st.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?st.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?st.FS_MAX_FLOAT_PRECISION="mediump":st.FS_MAX_FLOAT_PRECISION="lowp":st.FS_MAX_FLOAT_PRECISION="mediump",st.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),st.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),st.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),st.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),st.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),st.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),st.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),st.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),st.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),st.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){st.SUPPORTED_EXTENSIONS[e]=!0})))}const ot=h.vec3(),nt=new e({}),at=function(e,t){this.id=nt.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new We(t),this._allocate(t)},lt={};at.get=function(e){const t=e.scene,i=[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 s=lt[i];if(!s){if(s=new at(i,e),s.errors)return console.log(s.errors.join("\n")),null;lt[i]=s,p.memory.programs++}return s._useCount++,s},at.prototype.put=function(){0==--this._useCount&&(nt.removeItem(this.id),this._program&&this._program.destroy(),delete lt[this._hash],p.memory.programs--)},at.prototype.webglContextRestored=function(){this._program=null},at.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=st.MAX_TEXTURE_UNITS,s=t.scene,r=t._material,o=s.canvas.gl,n=this._program,a=t._state,l=t._material._state,A=t._geometry._state,c=s.camera,h=t.origin,u=a.background;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,u&&o.depthFunc(o.LEQUAL),this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):c.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,c.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(h){const t=ze(i.dist,i.dir,h,ot);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}if(l.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=l.backfaces;e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t);const s=l.frontface;switch(e.frontface!==s&&(s?o.frontFace(o.CCW):o.frontFace(o.CW),e.frontface=s),e.lineWidth!==l.lineWidth&&(o.lineWidth(l.lineWidth),e.lineWidth=l.lineWidth),this._uPointSize&&o.uniform1f(this._uPointSize,l.pointSize),l.type){case"LambertMaterial":this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialColor&&o.uniform4f(this._uMaterialColor,l.color[0],l.color[1],l.color[2],l.alpha),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive);break;case"PhongMaterial":this._uMaterialShininess&&o.uniform1f(this._uMaterialShininess,l.shininess),this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0),r._ambientMap&&r._ambientMap._state.texture&&this._uMaterialAmbientMap&&(n.bindTexture(this._uMaterialAmbientMap,r._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMaterialAmbientMapMatrix&&o.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,r._ambientMap._state.matrix)),r._diffuseMap&&r._diffuseMap._state.texture&&this._uDiffuseMap&&(n.bindTexture(this._uDiffuseMap,r._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,r._diffuseMap._state.matrix)),r._specularMap&&r._specularMap._state.texture&&this._uSpecularMap&&(n.bindTexture(this._uSpecularMap,r._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,r._specularMap._state.matrix)),r._emissiveMap&&r._emissiveMap._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,r._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,r._emissiveMap._state.matrix)),r._alphaMap&&r._alphaMap._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,r._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,r._alphaMap._state.matrix)),r._reflectivityMap&&r._reflectivityMap._state.texture&&this._uReflectivityMap&&(n.bindTexture(this._uReflectivityMap,r._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,this._uReflectivityMapMatrix&&o.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,r._reflectivityMap._state.matrix)),r._normalMap&&r._normalMap._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,r._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,r._normalMap._state.matrix)),r._occlusionMap&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,r._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,r._occlusionMap._state.matrix)),r._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&o.uniform1f(this._uDiffuseFresnelEdgeBias,r._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&o.uniform1f(this._uDiffuseFresnelCenterBias,r._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&o.uniform3fv(this._uDiffuseFresnelEdgeColor,r._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&o.uniform3fv(this._uDiffuseFresnelCenterColor,r._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&o.uniform1f(this._uDiffuseFresnelPower,r._diffuseFresnel.power)),r._specularFresnel&&(this._uSpecularFresnelEdgeBias&&o.uniform1f(this._uSpecularFresnelEdgeBias,r._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&o.uniform1f(this._uSpecularFresnelCenterBias,r._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&o.uniform3fv(this._uSpecularFresnelEdgeColor,r._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&o.uniform3fv(this._uSpecularFresnelCenterColor,r._specularFresnel.centerColor),this._uSpecularFresnelPower&&o.uniform1f(this._uSpecularFresnelPower,r._specularFresnel.power)),r._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&o.uniform1f(this._uAlphaFresnelEdgeBias,r._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&o.uniform1f(this._uAlphaFresnelCenterBias,r._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&o.uniform3fv(this._uAlphaFresnelEdgeColor,r._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&o.uniform3fv(this._uAlphaFresnelCenterColor,r._alphaFresnel.centerColor),this._uAlphaFresnelPower&&o.uniform1f(this._uAlphaFresnelPower,r._alphaFresnel.power)),r._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&o.uniform1f(this._uReflectivityFresnelEdgeBias,r._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&o.uniform1f(this._uReflectivityFresnelCenterBias,r._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&o.uniform3fv(this._uReflectivityFresnelEdgeColor,r._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&o.uniform3fv(this._uReflectivityFresnelCenterColor,r._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&o.uniform1f(this._uReflectivityFresnelPower,r._reflectivityFresnel.power)),r._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&o.uniform1f(this._uEmissiveFresnelEdgeBias,r._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&o.uniform1f(this._uEmissiveFresnelCenterBias,r._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&o.uniform3fv(this._uEmissiveFresnelEdgeColor,r._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&o.uniform3fv(this._uEmissiveFresnelCenterColor,r._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&o.uniform1f(this._uEmissiveFresnelPower,r._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&o.uniform3fv(this._uBaseColor,l.baseColor),this._uMaterialMetallic&&o.uniform1f(this._uMaterialMetallic,l.metallic),this._uMaterialRoughness&&o.uniform1f(this._uMaterialRoughness,l.roughness),this._uMaterialSpecularF0&&o.uniform1f(this._uMaterialSpecularF0,l.specularF0),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const t=r._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(n.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uBaseColorMapMatrix&&o.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const s=r._metallicMap;s&&s._state.texture&&this._uMetallicMap&&(n.bindTexture(this._uMetallicMap,s._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicMapMatrix&&o.uniformMatrix4fv(this._uMetallicMapMatrix,!1,s._state.matrix));const a=r._roughnessMap;a&&a._state.texture&&this._uRoughnessMap&&(n.bindTexture(this._uRoughnessMap,a._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uRoughnessMapMatrix&&o.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,a._state.matrix));const A=r._metallicRoughnessMap;A&&A._state.texture&&this._uMetallicRoughnessMap&&(n.bindTexture(this._uMetallicRoughnessMap,A._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&o.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,A._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(f=r._alphaMap)&&f._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(m=r._normalMap)&&m._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,m._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialGlossiness&&o.uniform1f(this._uMaterialGlossiness,l.glossiness),this._uMaterialReflectivity&&o.uniform1f(this._uMaterialReflectivity,l.reflectivity),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const c=r._diffuseMap;c&&c._state.texture&&this._uDiffuseMap&&(n.bindTexture(this._uDiffuseMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,c._state.matrix));const h=r._specularMap;h&&h._state.texture&&this._uSpecularMap&&(n.bindTexture(this._uSpecularMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,h._state.matrix));const u=r._glossinessMap;u&&u._state.texture&&this._uGlossinessMap&&(n.bindTexture(this._uGlossinessMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uGlossinessMapMatrix&&o.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,u._state.matrix));const g=r._specularGlossinessMap;var d,p,f,m;g&&g._state.texture&&this._uSpecularGlossinessMap&&(n.bindTexture(this._uSpecularGlossinessMap,g._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&o.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,g._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(n.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&p._state.texture&&this._uOcclusionMap&&(n.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(f=r._alphaMap)&&f._state.texture&&this._uAlphaMap&&(n.bindTexture(this._uAlphaMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,f._state.matrix)),(m=r._normalMap)&&m._state.texture&&this._uNormalMap&&(n.bindTexture(this._uNormalMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,m._state.matrix))}this._lastMaterialId=l.id}if(o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),this._uColorize){const e=a.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(o.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}o.uniform3fv(this._uOffset,a.offset),o.uniform3fv(this._uScale,t.scale),A.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,A.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,A.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(A.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(A.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(A.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(A.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(A.flagsBuf),e.bindArray++),A.indicesBuf&&(A.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=A.id),A.indicesBuf?(o.drawElements(A.primitive,A.indicesBuf.numItems,A.indicesBuf.itemType,0),e.drawElements++):A.positions&&(o.drawArrays(o.TRIANGLES,0,A.positions.numItems),e.drawArrays++),u&&o.depthFunc(o.LESS)},at.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=e._material,r=t._lightsState,o=t._sectionPlanesState,n=e._material._state;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const a=this._program;this._uPositionsDecodeMatrix=a.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=a.getLocation("uvDecodeMatrix"),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._uGammaFactor=a.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=a.getLocation("logDepthBufFC"));const l=r.lights;let A;for(var c=0,h=l.length;c<h;c++){switch(A=l[c],A.type){case"ambient":this._uLightAmbient[c]=a.getLocation("lightAmbient");break;case"dir":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=null,this._uLightDir[c]=a.getLocation("lightDir"+c);break;case"point":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=null,this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c);break;case"spot":this._uLightColor[c]=a.getLocation("lightColor"+c),this._uLightPos[c]=a.getLocation("lightPos"+c),this._uLightDir[c]=a.getLocation("lightDir"+c),this._uLightAttenuation[c]=a.getLocation("lightAttenuation"+c)}A.castsShadow&&(this._uShadowViewMatrix[c]=a.getLocation("shadowViewMatrix"+c),this._uShadowProjMatrix[c]=a.getLocation("shadowProjMatrix"+c))}r.lightMaps.length>0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(c=0,h=o.sectionPlanes.length;c<h;c++)this._uSectionPlanes.push({active:a.getLocation("sectionPlaneActive"+c),pos:a.getLocation("sectionPlanePos"+c),dir:a.getLocation("sectionPlaneDir"+c)});switch(this._uPointSize=a.getLocation("pointSize"),n.type){case"LambertMaterial":this._uMaterialColor=a.getLocation("materialColor"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=a.getLocation("materialAmbient"),this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=a.getLocation("materialShininess"),s._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=a.getLocation("ambientMapMatrix")),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=a.getLocation("reflectivityMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=a.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=a.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=a.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=a.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=a.getLocation("diffuseFresnelPower")),s._specularFresnel&&(this._uSpecularFresnelEdgeBias=a.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=a.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=a.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=a.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=a.getLocation("specularFresnelPower")),s._alphaFresnel&&(this._uAlphaFresnelEdgeBias=a.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=a.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=a.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=a.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=a.getLocation("alphaFresnelPower")),s._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=a.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=a.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=a.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=a.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=a.getLocation("reflectivityFresnelPower")),s._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=a.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=a.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=a.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=a.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=a.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=a.getLocation("materialBaseColor"),this._uMaterialMetallic=a.getLocation("materialMetallic"),this._uMaterialRoughness=a.getLocation("materialRoughness"),this._uMaterialSpecularF0=a.getLocation("materialSpecularF0"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),s._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=a.getLocation("baseColorMapMatrix")),s._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=a.getLocation("metallicMapMatrix")),s._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=a.getLocation("roughnessMapMatrix")),s._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=a.getLocation("metallicRoughnessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=a.getLocation("materialDiffuse"),this._uMaterialSpecular=a.getLocation("materialSpecular"),this._uMaterialGlossiness=a.getLocation("materialGlossiness"),this._uMaterialReflectivity=a.getLocation("reflectivityFresnel"),this._uMaterialEmissive=a.getLocation("materialEmissive"),this._uAlphaModeCutoff=a.getLocation("materialAlphaModeCutoff"),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=a.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=a.getLocation("specularMapMatrix")),s._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=a.getLocation("glossinessMapMatrix")),s._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=a.getLocation("materialSpecularGlossinessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=a.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=a.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=a.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=a.getLocation("normalMapMatrix"))}this._aPosition=a.getAttribute("position"),this._aNormal=a.getAttribute("normal"),this._aUV=a.getAttribute("uv"),this._aColor=a.getAttribute("color"),this._aFlags=a.getAttribute("flags"),this._uClippable=a.getLocation("clippable"),this._uColorize=a.getLocation("colorize"),this._uOffset=a.getLocation("offset"),this._uScale=a.getLocation("scale"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},at.prototype._bindProgram=function(e){const t=st.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=i._lightsState,o=i.camera.project;let n;const a=this._program;if(a.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,s.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(var l=0,A=r.lights.length;l<A;l++)if(n=r.lights[l],this._uLightAmbient[l])s.uniform4f(this._uLightAmbient[l],n.color[0],n.color[1],n.color[2],n.intensity);else if(this._uLightColor[l]&&s.uniform4f(this._uLightColor[l],n.color[0],n.color[1],n.color[2],n.intensity),this._uLightPos[l]&&(s.uniform3fv(this._uLightPos[l],n.pos),this._uLightAttenuation[l]&&s.uniform1f(this._uLightAttenuation[l],n.attenuation)),this._uLightDir[l]&&s.uniform3fv(this._uLightDir[l],n.dir),n.castsShadow){this._uShadowViewMatrix[l]&&s.uniformMatrix4fv(this._uShadowViewMatrix[l],!1,n.getShadowViewMatrix()),this._uShadowProjMatrix[l]&&s.uniformMatrix4fv(this._uShadowProjMatrix[l],!1,n.getShadowProjMatrix());const i=n.getShadowRenderBuf();i&&(a.bindTexture("shadowMap"+l,i.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class At{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=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),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),l.push("uniform vec3 scale;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.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;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(l.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&l.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&l.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&l.push("uniform vec3 lightPos"+e+";"))}o&&(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("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = scale[0];"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = scale[1];"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(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;"),s)for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?l.push("viewLightDir = normalize(lightDir"+e+");"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?l.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}l.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),r&&l.push("vWorldPosition = worldPosition;");"points"===e._geometry._state.primitiveName&&l.push("gl_PointSize = pointSize;");l.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(l.push("vFragDepth = 1.0 + clipPos.w;"),l.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return l.push("gl_Position = clipPos;"),l.push("}"),l}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ct=new e({}),ht=h.vec3(),ut=function(e,t){this.id=ct.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new At(t),this._allocate(t)},dt={};ut.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 i=dt[t];return i||(i=new ut(t,e),dt[t]=i,p.memory.programs++),i._useCount++,i},ut.prototype.put=function(){0==--this._useCount&&(ct.removeItem(this.id),this._program&&this._program.destroy(),delete dt[this._hash],p.memory.programs--)},ut.prototype.webglContextRestored=function(){this._program=null},ut.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(A){const t=ze(i.dist,i.dir,A,ht);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}if(n.id!==this._lastMaterialId){const t=n.fillColor,i=n.backfaces;e.backfaces!==i&&(i?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=i),o.uniform4f(this._uFillColor,t[0],t[1],t[2],n.fillAlpha),this._lastMaterialId=n.id}o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),o.uniform3fv(this._uOffset,a.offset),l.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(l.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(l.normalsBuf),e.bindArray++),l.indicesBuf?(l.indicesBuf.bind(),e.bindArray++):l.positionsBuf,this._lastGeometryId=l.id),l.indicesBuf?(o.drawElements(l.primitive,l.indicesBuf.numItems,l.indicesBuf.itemType,0),e.drawElements++):l.positionsBuf&&(o.drawArrays(o.TRIANGLES,0,l.positionsBuf.numItems),e.drawArrays++)},ut.prototype._allocate=function(e){const t=e.scene,i=t._lightsState,s=t._sectionPlanesState,r=t.canvas.gl;if(this._program=new it(r,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const o=this._program;this._uPositionsDecodeMatrix=o.getLocation("positionsDecodeMatrix"),this._uModelMatrix=o.getLocation("modelMatrix"),this._uModelNormalMatrix=o.getLocation("modelNormalMatrix"),this._uViewMatrix=o.getLocation("viewMatrix"),this._uViewNormalMatrix=o.getLocation("viewNormalMatrix"),this._uProjMatrix=o.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=i.lights.length;e<t;e++){switch(i.lights[e].type){case"ambient":this._uLightAmbient[e]=o.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=o.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=o.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=o.getLocation("lightAttenuation"+e)}}this._uSectionPlanes=[];for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)this._uSectionPlanes.push({active:o.getLocation("sectionPlaneActive"+e),pos:o.getLocation("sectionPlanePos"+e),dir:o.getLocation("sectionPlaneDir"+e)});this._uFillColor=o.getLocation("fillColor"),this._aPosition=o.getAttribute("position"),this._aNormal=o.getAttribute("normal"),this._uClippable=o.getLocation("clippable"),this._uGammaFactor=o.getLocation("gammaFactor"),this._uOffset=o.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=o.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},ut.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._lightsState,r=t.camera,o=r.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,i.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.normalMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];this._uLightAmbient[e]?i.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor)};class pt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),n.push("uniform vec3 scale;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = scale[0];"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = scale[1];"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));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("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ft=new e({}),mt=h.vec3(),gt=function(e,t){this.id=ft.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new pt(t),this._allocate(t)},_t={};gt.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 i=_t[t];return i||(i=new gt(t,e),_t[t]=i,p.memory.programs++),i._useCount++,i},gt.prototype.put=function(){0==--this._useCount&&(ft.removeItem(this.id),this._program&&this._program.destroy(),delete _t[this._hash],p.memory.programs--)},gt.prototype.webglContextRestored=function(){this._program=null},gt.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(a.originHash,c):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<i){const i=n.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,i?1:0),i){const i=r[t];if(c){const t=ze(i.dist,i.dir,c,mt);o.uniform3fv(e.pos,t)}else o.uniform3fv(e.pos,i.pos);o.uniform3fv(e.dir,i.dir)}}else o.uniform1i(e.active,0)}}}switch(i){case 0:n=t._xrayMaterial._state;break;case 1:n=t._highlightMaterial._state;break;case 2:n=t._selectedMaterial._state;break;default:n=t._edgeMaterial._state}if(n.id!==this._lastMaterialId){const t=n.backfaces;if(e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t),e.lineWidth!==n.edgeWidth&&(o.lineWidth(n.edgeWidth),e.lineWidth=n.edgeWidth),this._uEdgeColor){const e=n.edgeColor,t=n.edgeAlpha;o.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=n.id}let h;o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uClippable&&o.uniform1i(this._uClippable,a.clippable),o.uniform3fv(this._uOffset,a.offset),A.primitive===o.TRIANGLES?h=l._getEdgeIndices():A.primitive===o.LINES&&(h=A.indicesBuf),h&&(A.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,A.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(A.positionsBuf,A.compressGeometry?o.UNSIGNED_SHORT:o.FLOAT),e.bindArray++),h.bind(),e.bindArray++,this._lastGeometryId=A.id),o.drawElements(o.LINES,h.numItems,h.itemType,0),e.drawElements++)},gt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+e),pos:r.getLocation("sectionPlanePos"+e),dir:r.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=r.getLocation("edgeColor"),this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uGammaFactor=r.getLocation("gammaFactor"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},gt.prototype._bindProgram=function(e){const t=this._program,i=this._scene,s=i.canvas.gl,r=i.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)};class vt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),n.push("uniform vec3 scale;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = scale[0];"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = scale[1];"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking 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(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const bt=h.vec3(),yt=function(e,t){this._hash=e,this._shaderSource=new vt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},wt={};yt.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=wt[t];if(!i){if(i=new yt(t,e),i.errors)return console.log(i.errors.join("\n")),null;wt[t]=i,p.memory.programs++}return i._useCount++,i},yt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete wt[this._hash],p.memory.programs--)},yt.prototype.webglContextRestored=function(){this._program=null},yt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(a){const t=ze(i.dist,i.dir,a,bt);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}if(o.id!==this._lastMaterialId){const t=o.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=o.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=o.id}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=n.id);var l=t._state.pickID;const A=l>>24&255,c=l>>16&255,h=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,h/255,c/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},yt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uPickColor=s.getLocation("pickColor"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},yt.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class Bt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),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;"));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("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),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,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking 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"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e<i.getNumAllocatedSectionPlanes();e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0;e<i.getNumAllocatedSectionPlanes();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("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const xt=h.vec3(),Pt=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Bt(t),this._allocate(t)},Ct={};Pt.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Ct[t];if(!i){if(i=new Pt(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ct[t]=i,p.memory.programs++}return i._useCount++,i},Pt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ct[this._hash],p.memory.programs--)},Pt.prototype.webglContextRestored=function(){this._program=null},Pt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,c=o.frontface,h=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(h.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(l){const t=ze(i.dist,i.dir,l,xt);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled&&s.uniform1f(this._uZFar,i.camera.project.far),e.backfaces!==A&&(A?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=A),e.frontface!==c&&(c?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=c),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(u,a.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT)):this._aPosition.bindArrayBuffer(u),s.uniform2fv(this._uPickClipPos,e.pickClipPos),d.bind(),s.enableVertexAttribArray(this._aColor.location),s.vertexAttribPointer(this._aColor.location,d.itemSize,d.itemType,!0,0,0),s.drawArrays(a.primitive,0,u.numItems/3)},Pt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))};class Mt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),n.push("uniform vec3 scale;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = scale[0];"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = scale[1];"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));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("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion 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(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Ft=h.vec3(),Et=function(e,t){this._hash=e,this._shaderSource=new Mt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},It={};Et.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=It[t];if(!i){if(i=new Et(t,e),i.errors)return console.log(i.errors.join("\n")),null;It[t]=i,p.memory.programs++}return i._useCount++,i},Et.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete It[this._hash],p.memory.programs--)},Et.prototype.webglContextRestored=function(){this._program=null},Et.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t];if(e)if(t<r){const i=n.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=o[t];if(a){const t=ze(i.dist,i.dir,a,Ft);s.uniform3fv(e.pos,t)}else s.uniform3fv(e.pos,i.pos);s.uniform3fv(e.dir,i.dir)}}else s.uniform1i(e.active,0)}}}s.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix),s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),n.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(n.positionsBuf,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),n.indicesBuf&&(n.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=n.id),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Et.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Et.prototype._bindProgram=function(e){const t=this._scene,i=t.camera.project,s=t.canvas.gl;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Tt{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow 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"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("vec4 encodeFloat( const in float depth ) {"),r.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),r.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),r.push(" vec4 comp = fract(depth * bitShift);"),r.push(" comp -= comp.xxyz * bitMask;"),r.push(" return comp;"),r.push("}"),r.push("out vec4 outColor;"),r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push(" float dist = 0.0;");for(o=0;o<i.getNumAllocatedSectionPlanes();o++)r.push("if (sectionPlaneActive"+o+") {"),r.push(" dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push(" if (dist > 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Dt=function(e,t){this._hash=e,this._shaderSource=new Tt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},St={};Dt.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=St[i];if(!s){if(s=new Dt(i,e),s.errors)return console.log(s.errors.join("\n")),null;St[i]=s,p.memory.programs++}return s._useCount++,s},Dt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete St[this._hash],p.memory.programs--)},Dt.prototype.webglContextRestored=function(){this._program=null},Dt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Dt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new it(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Dt.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.getNumAllocatedSectionPlanes()>0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a<l;a++)e=this._uSectionPlanes[a],t=e.active,r=s.sectionPlanes[a],t&&i.uniform1i(t,r.active),o=e.pos,o&&i.uniform3fv(e.pos,r.pos),n=e.dir,n&&i.uniform3fv(e.dir,r.dir)}};class Rt{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 Ut=h.OBB3(),Lt=h.vec4(),kt=h.vec4(),Ot=h.vec4(),Nt=h.vec3([1,0,0]),Vt=h.vec3([0,1,0]),Qt=h.vec3([0,0,1]),Ht=h.vec3(3),Gt=h.vec3(3),jt=h.identityMat4();class zt extends T{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Rt,this._state=new ie({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,isUI:t.isUI}),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 i=t.origin||t.rtcCenter;if(i&&(this._state.origin=h.vec3(i),this._state.originHash=i.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||jt),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 isUI(){return this._state.isUI}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 i=!!e;this.scene._objectColorizeUpdated(this,i),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 i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),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=at.get(this),this._emphasisFillRenderer=ut.get(this),this._emphasisEdgesRenderer=gt.get(this));const t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=yt.get(this)),this._state.occluder){const e=this._makeOcclusionHash();this._state.occlusionHash!==e&&(this._state.occlusionHash=e,this._putOcclusionRenderer(),this._occlusionRenderer=Et.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,i=e.length;t<i;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()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),i.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){h.transformOBB3(e,this._geometry.obb,Ut),h.OBB3ToAABB3(Ut,t);const i=this._state.offset;if(t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[0],t[4]+=i[1],t[5]+=i[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 Lt[0]=e[0],Lt[1]=e[1],Lt[2]=e[2],Lt[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Lt,kt),h.mulQuaternions(this.quaternion,kt,Ot),this.quaternion=Ot,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Lt[0]=e[0],Lt[1]=e[1],Lt[2]=e[2],Lt[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Lt,kt),h.mulQuaternions(kt,this.quaternion,kt),this}rotateX(e){return this.rotate(Nt,e)}rotateY(e){return this.rotate(Vt,e)}rotateZ(e){return this.rotate(Qt,e)}translate(e,t){return h.vec3ApplyQuaternion(this.quaternion,e,Ht),h.mulVec3Scalar(Ht,t,Gt),h.addVec3(this.position,Gt,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Nt,e)}translateY(e){return this.translate(Vt,e)}translateZ(e){return this.translate(Qt,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 i=0;i<t;i++){const t=e[i],s=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 r=0===e;s.sectionPlanesActivePerLayer[i]=r}else s.sectionPlanesActivePerLayer[i]=!0;else s.sectionPlanesActivePerLayer[i]=!1}}return!0}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=at.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=at.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=ut.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=ut.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=ut.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=gt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._state.occluder&&this._occlusionRenderer||(this._occlusionRenderer=Et.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=Dt.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=yt.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=Pt.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,i,s){Wt(this,e,t,i,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 Wt=function(){const e=h.vec3(),t=h.vec3(),i=h.vec3(),s=h.vec3(),r=h.vec3(),o=h.vec3(),n=h.vec4(),a=h.vec3(),l=h.vec3(),A=h.vec3(),c=h.vec3(),u=h.vec3(),d=h.vec3(),p=h.vec3(),f=h.vec3(),m=h.vec3(),g=h.vec4(),_=h.vec4(),v=h.vec4(),b=h.vec3(),y=h.vec3(),w=h.vec3(),B=h.vec3(),x=h.vec3(),P=h.vec3(),C=h.vec3(),M=h.vec3(),F=h.vec3(),E=h.vec3(),I=h.vec3();return function(T,D,S,R,U){var L=U.primIndex;if(null!=L&&L>-1){const V=T.geometry._state,Q=T.scene,H=Q.camera,G=Q.canvas;if("triangles"===V.primitiveName){U.primitive="triangle";const Q=L,j=V.indices,z=V.positions;let W,X,K;if(j){var k=j[Q+0],O=j[Q+1],N=j[Q+2];o[0]=k,o[1]=O,o[2]=N,U.indices=o,W=3*k,X=3*O,K=3*N}else W=3*Q,X=W+3,K=X+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[X+0],s[1]=z[X+1],s[2]=z[X+2],r[0]=z[K+0],r[1]=z[K+1],r[2]=z[K+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(he.decompressPosition(i,e,i),he.decompressPosition(s,e,s),he.decompressPosition(r,e,r))}U.canvasPos?h.canvasPosToLocalRay(G.canvas,T.origin?He(D,T.origin):D,S,R,T.worldMatrix,U.canvasPos,e,t):U.origin&&U.direction&&h.worldRayToLocalRay(T.worldMatrix,U.origin,U.direction,e,t),h.normalizeVec3(t),h.rayPlaneIntersect(e,t,i,s,r,n),U.localPos=n,U.position=n,g[0]=n[0],g[1]=n[1],g[2]=n[2],g[3]=1,h.transformVec4(T.worldMatrix,g,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],U.canvasPos&&T.origin&&(a[0]+=T.origin[0],a[1]+=T.origin[1],a[2]+=T.origin[2]),U.worldPos=a,h.transformVec4(H.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],U.viewPos=l,h.cartesianToBarycentric(n,i,s,r,A),U.bary=A;const Z=V.normals;if(Z){if(V.compressGeometry){const e=3*k,t=3*O,i=3*N;he.decompressNormal(Z.subarray(e,e+2),c),he.decompressNormal(Z.subarray(t,t+2),u),he.decompressNormal(Z.subarray(i,i+2),d)}else c[0]=Z[W],c[1]=Z[W+1],c[2]=Z[W+2],u[0]=Z[X],u[1]=Z[X+1],u[2]=Z[X+2],d[0]=Z[K],d[1]=Z[K+1],d[2]=Z[K+2];const e=h.addVec3(h.addVec3(h.mulVec3Scalar(c,A[0],b),h.mulVec3Scalar(u,A[1],y),w),h.mulVec3Scalar(d,A[2],B),x);U.worldNormal=h.normalizeVec3(h.transformVec3(T.worldNormalMatrix,e,P))}const J=V.uv;if(J){if(p[0]=J[2*k],p[1]=J[2*k+1],f[0]=J[2*O],f[1]=J[2*O+1],m[0]=J[2*N],m[1]=J[2*N+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(he.decompressUV(p,e,p),he.decompressUV(f,e,f),he.decompressUV(m,e,m))}U.uv=h.addVec3(h.addVec3(h.mulVec2Scalar(p,A[0],C),h.mulVec2Scalar(f,A[1],M),F),h.mulVec2Scalar(m,A[2],E),I)}}}}}();class Xt extends T{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Kt={opaque:0,mask:1,blend:2},Zt=["opaque","mask","blend"];class Jt extends Xt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({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=Kt[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 Zt[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()}}function Yt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=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":i=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":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}function qt(e,t,i=null){let s;const r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===i){const t=Yt(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===r)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(s=Yt(e,"WEBGL_compressed_texture_s3tc"),null===s)return null;if(33776===r)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){const t=Yt(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===r)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){const t=Yt(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){const t=Yt(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===r)return 3001===i?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){const t=Yt(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){const t=Yt(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===r)return 3001===i?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}const $t=new Uint8Array([0,0,0,1]);class ei{constructor({gl:e,target:t,format:i,type:s,wrapS:r,wrapT:o,wrapR:n,encoding:a,preloadColor:l,premultiplyAlpha:A,flipY:c}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=i||1023,this.type=s||1009,this.internalFormat=null,this.premultiplyAlpha=!!A,this.flipY=!!c,this.unpackAlignment=4,this.wrapS=r||1e3,this.wrapT=o||1e3,this.wrapR=n||1e3,this.encoding=a||3001,this.texture=e.createTexture(),l&&this.setPreloadColor(l),this.allocated=!0}setPreloadColor(e){e?($t[0]=Math.floor(255*e[0]),$t[1]=Math.floor(255*e[1]),$t[2]=Math.floor(255*e[2]),$t[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):($t[0]=0,$t[1]=0,$t[2]=0,$t[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 i=0,s=e.length;i<s;i++)t.texImage2D(e[i],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,$t)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,$t);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const i=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 s=!1;i.bindTexture(this.target,this.texture);const r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);const o=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const n=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);const a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const l=qt(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(s=!0);const A=qt(i,this.magFilter);A&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,A);const c=qt(i,this.wrapS);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,c);const h=qt(i,this.wrapT);h&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,h);const u=qt(i,this.format,this.encoding),d=qt(i,this.type),p=ti(i,this.internalFormat,u,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(_.isArray(e)){const t=e,s=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,r=s.length;e<r;e++)i.texImage2D(s[e],0,p,u,d,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,p,u,d,e);s&&i.generateMipmap(this.target),i.bindTexture(this.target,null),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,r),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o),i.pixelStorei(i.UNPACK_ALIGNMENT,n),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,a)}setCompressedData({mipmaps:e,props:t={}}){const i=this.gl,s=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),i.activeTexture(i.TEXTURE0+0),i.bindTexture(this.target,this.texture);let r=e.length>1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=qt(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=qt(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=qt(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ii(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ii(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,qt(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,qt(i,this.magFilter)));const a=qt(i,this.format,this.encoding),l=qt(i,this.type),A=ti(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t<s;t++){const s=e[t];1023!==this.format?null!==a?i.compressedTexSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,a,s.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):i.texSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,a,l,s.data)}i.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 i=qt(t,e.minFilter);i&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,i),i!==t.NEAREST_MIPMAP_NEAREST&&i!==t.LINEAR_MIPMAP_NEAREST&&i!==t.NEAREST_MIPMAP_LINEAR&&i!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const i=qt(t,e.magFilter);i&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i))}if(void 0!==e.wrapS){const i=qt(t,e.wrapS);i&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,i))}if(void 0!==e.wrapT){const i=qt(t,e.wrapT);i&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,i))}}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 ti(e,t,i,s,r,o=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let n=i;return i===e.RED&&(s===e.FLOAT&&(n=e.R32F),s===e.HALF_FLOAT&&(n=e.R16F),s===e.UNSIGNED_BYTE&&(n=e.R8)),i===e.RG&&(s===e.FLOAT&&(n=e.RG32F),s===e.HALF_FLOAT&&(n=e.RG16F),s===e.UNSIGNED_BYTE&&(n=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(n=e.RGBA32F),s===e.HALF_FLOAT&&(n=e.RGBA16F),s===e.UNSIGNED_BYTE&&(n=3001===r&&!1===o?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(n=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(n=e.RGB5_A1)),n!==e.R16F&&n!==e.R32F&&n!==e.RG16F&&n!==e.RG32F&&n!==e.RGBA16F&&n!==e.RGBA32F||Yt(e,"EXT_color_buffer_float"),n}function ii(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function si(e){if(!ri(e.width)||!ri(e.height)){const t=document.createElement("canvas");t.width=oi(e.width),t.height=oi(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function ri(e){return 0==(e&e-1)}function oi(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class ni extends T{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new ie({texture:new ei({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),p.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 ei({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,i;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]||(i=h.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?h.mulMat4(t,i):i),0!==this._rotate&&(i=h.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?h.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=si(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 i=new Image;i.onload=function(){i=si(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.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(),p.memory.textures--}}const ai=h.vec3(),li=h.vec3();h.vec3();const Ai=h.vec3([0,-1,0]),ci=h.vec4([0,0,0,1]);class hi extends Xt{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({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 ui={opaque:0,mask:1,blend:2},di=["opaque","mask","blend"];class pi extends Xt{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({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=ui[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 di[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 fi={opaque:0,mask:1,blend:2},mi=["opaque","mask","blend"];class gi extends Xt{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new ie({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=fi[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 mi[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 _i={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 vi extends Xt{get type(){return"EmphasisMaterial"}get presets(){return _i}constructor(e,t={}){super(e,t),this._state=new ie({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(console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),e=e||"default",this._preset===e)return;const t=_i[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(_i).join(", "))}get preset(){return console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),this._preset}destroy(){super.destroy(),this._state.destroy()}}const bi={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 yi extends Xt{get type(){return"EdgeMaterial"}get presets(){return bi}constructor(e,t={}){super(e,t),this._state=new ie({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=bi[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(bi).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}class wi extends T{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 ni(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 Ne(this,{matrix:h.inverseMat4(h.lookAtMat4v(this._pos,h.subVec3(this._pos,this._normal,h.mat4()),this._up,h.mat4())),children:[this._bitmapMesh=new zt(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new pe(this,Be({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Jt(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]}}const Bi=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let o=0;o<3;o++)if(s=t[3*e+o],r=t[3*i+o],s!==r)return r-s;return 0}let o=e.slice().sort(r),n=null;for(let e=0,t=o.length;e<t;e++)0!==e&&0===r(o[e],o[e-1])||(n=o[e]),i[o[e]]=n;for(let t=0,r=e.length;t<r;t+=3){const r=i[e[t]],o=i[e[t+1]],n=i[e[t+2]];let a=r,l=o,A=n;if(r>o&&r>n?o>n?(a=r,l=o,A=n):(a=r,l=n,A=o):o>r&&o>n?r>n?(a=o,l=r,A=n):(a=o,l=n,A=r):n>r&&n>o&&(r>o?(a=n,l=r,A=o):(a=n,l=o,A=r)),s[t+0]=[a,l],s[t+1]=[l,A],a>A){const e=A;A=a,a=e}s[t+2]=[A,a]}function a(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(a);let l=0;for(let e=0;e<s.length;e++)if(0===e||0!==a(s[e],s[e-1])){if(0!==e&&2!==l)return!1;l=1}else l++;return!(s.length>0&&2!==l)},xi=h.vec3(),Pi=h.vec3(),Ci=h.vec3();class Mi{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!Bi(t,e))return-1;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],o=3*t[s+1],n=3*t[s+2];xi[0]=e[r],xi[1]=e[r+1],xi[2]=e[r+2],Pi[0]=e[o],Pi[1]=e[o+1],Pi[2]=e[o+2],Ci[0]=e[n],Ci[1]=e[n+1],Ci[2]=e[n+2],h.cross3Vec3(xi,Pi,xi),i+=h.dotVec3(xi,Ci)}return i/6}}const Fi=new Mi,Ei=h.vec3(),Ii=h.vec3(),Ti=h.vec3(),Di=h.vec3(),Si=h.vec3(),Ri=h.vec3();class Ui{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get surfaceArea(){const e=this.vertices,t=this.indices;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],o=3*t[s+1],n=3*t[s+2];Ei[0]=e[r],Ei[1]=e[r+1],Ei[2]=e[r+2],Ii[0]=e[o],Ii[1]=e[o+1],Ii[2]=e[o+2],Ti[0]=e[n],Ti[1]=e[n+1],Ti[2]=e[n+2],h.subVec3(Ei,Ii,Di),h.subVec3(Ti,Ii,Si),i+=.5*h.lenVec3(h.cross3Vec3(Di,Si,Ri))}return i}}const Li=new Ui,ki=h.OBB3(),Oi=h.OBB3(),Ni=h.OBB3();class Vi{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=h.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this),this._volume=null,this._surfaceArea=null}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.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 i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_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,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}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.layer.getEachVertex(this.portionId,e)}getEachIndex(e){this.layer.getEachIndex&&this.layer.getEachIndex(this.portionId,e)}isSolid(){return this.layer.solid}get volume(){if(null!==this._volume)return this._volume;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Fi.reset(),Fi.setPrimitive(this.layer.primitive),this.getEachVertex((e=>{Fi.addVertex(e)})),this.getEachIndex((e=>{Fi.addIndex(e)})),this._volume=Fi.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Li.reset(),this.getEachVertex((e=>{Li.addVertex(e)})),this.getEachIndex((e=>{Li.addIndex(e)})),this._surfaceArea=Li.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(h.AABB3ToOBB3(this._aabbLocal,ki),this.transform?(h.transformOBB3(this.transform.worldMatrix,ki,Oi),h.transformOBB3(this.model.worldMatrix,Oi,Ni),h.OBB3ToAABB3(Ni,this._aabbWorld)):(h.transformOBB3(this.model.worldMatrix,ki,Oi),h.OBB3ToAABB3(Oi,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const Qi=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 Hi=0;const Gi=1,ji=4,zi=8,Wi=16,Xi=32,Ki=256,Zi=512,Ji=1024,Yi=2048,qi={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},$i=new Float32Array([1,1,1,1]),es=new Float32Array([0,0,0,1]),ts=h.vec4(),is=h.vec3(),ss=h.vec3(),rs=h.mat4();class os{constructor(e,t=!1,{instancing:i=!1,edges:s=!1,useAlphaCutoff:r=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._useAlphaCutoff=r,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:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t<o;t++){const r=this._uSectionPlanes[t];if(r)if(t<n){const o=A.sectionPlanesActivePerLayer[l+t];if(i.uniform1i(r.active,o?1:0),o){const o=a[t],n=e._state.origin;if(n){const e=ze(o.dist,o.dir,n,is,s.matrix);i.uniform3fv(r.pos,e)}else i.uniform3fv(r.pos,o.pos);i.uniform3fv(r.dir,o.dir)}}else i.uniform1i(r.active,0)}}}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uColor||(this._uColor=s.getLocation("silhouetteColor")),this._uUVDecodeMatrix=s.getLocation("uvDecodeMatrix"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uGammaFactor=s.getLocation("gammaFactor"),t.uniformBlockBinding(s.handle,t.getUniformBlockIndex(s.handle,"Matrices"),this._matricesUniformBlockBufferBindingPoint),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=s.getLocation("zFar")),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aUV=s.getAttribute("uv"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aPickColor=s.getAttribute("pickColor"),this._uPickZNear=s.getLocation("pickZNear"),this._uPickZFar=s.getLocation("pickZFar"),this._uPickClipPos=s.getLocation("pickClipPos"),this._uDrawingBufferSize=s.getLocation("drawingBufferSize"),this._uColorMap="uColorMap",this._uMetallicRoughMap="uMetallicRoughMap",this._uEmissiveMap="uEmissiveMap",this._uNormalMap="uNormalMap",this._uAOMap="uAOMap",this._instancing&&(this._aModelMatrix=s.getAttribute("modelMatrix"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=s.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=s.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=s.getAttribute("modelNormalMatrixCol2")),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),this._useAlphaCutoff&&(this._alphaCutoffLocation=s.getLocation("materialAlphaCutoff")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),e.pointsMaterial._state.filterIntensity&&(this._uIntensityRange=s.getLocation("intensityRange")),this._uPointSize=s.getLocation("pointSize"),this._uNearPlaneHeight=s.getLocation("nearPlaneHeight"),e.crossSections&&(this._uSliceColor=s.getLocation("sliceColor"),this._uSliceThickness=s.getLocation("sliceThickness"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState,o=r.lights;s.bind(),e.textureUnit=0,this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,r.getAmbientColorAndIntensity()),this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor);for(let e=0,t=o.length;e<t;e++){const t=o[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}}_makeVAO(e){const t=this._scene.canvas.gl,i=t.createVertexArray();return t.bindVertexArray(i),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?e.edgeIndicesBuf.bind():e.indicesBuf&&e.indicesBuf.bind(),i}drawLayer(e,t,i,{colorUniform:s=!1,incrementDrawState:r=!1}={}){const o=st.MAX_TEXTURE_IMAGE_UNITS,n=this._scene,a=n.canvas.gl,{_state:l,model:A}=t,{textureSet:c,origin:u,positionsDecodeMatrix:d}=l,p=n._lightsState,f=n.pointsMaterial,{camera:m}=A.scene,{viewNormalMatrix:g,project:_}=m,v=e.pickViewMatrix||m.viewMatrix,{position:b,rotationMatrix:y,worldNormalMatrix:w}=A;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)?a.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(l));let B=0;const x=16;this._matricesUniformBlockBufferData.set(y,0);const P=0!==u[0]||0!==u[1]||0!==u[2],C=0!==b[0]||0!==b[1]||0!==b[2];if(P||C){const e=is;if(P){const t=h.transformPoint3(y,u,ss);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=b[0],e[1]+=b[1],e[2]+=b[2],this._matricesUniformBlockBufferData.set(He(v,e,rs),B+=x)}else this._matricesUniformBlockBufferData.set(v,B+=x);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||_.matrix,B+=x),this._matricesUniformBlockBufferData.set(d,B+=x),this._matricesUniformBlockBufferData.set(w,B+=x),this._matricesUniformBlockBufferData.set(g,B+=x),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),a.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),n.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}this._uZFar&&a.uniform1f(this._uZFar,n.camera.project.far)}if(this._uPickInvisible&&a.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&a.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&a.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&a.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&a.uniform2f(this._uDrawingBufferSize,a.drawingBufferWidth,a.drawingBufferHeight),this._uUVDecodeMatrix&&a.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._uIntensityRange&&f.filterIntensity&&a.uniform2f(this._uIntensityRange,f.minIntensity,f.maxIntensity),this._uPointSize&&a.uniform1f(this._uPointSize,f.pointSize),this._uNearPlaneHeight){const e="ortho"===n.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*n.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,e)}if(c){const{colorTexture:t,metallicRoughnessTexture:i,emissiveTexture:s,normalsTexture:r,occlusionTexture:n}=c;this._uColorMap&&t&&(this._program.bindTexture(this._uColorMap,t.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uMetallicRoughMap&&i&&(this._program.bindTexture(this._uMetallicRoughMap,i.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uEmissiveMap&&s&&(this._program.bindTexture(this._uEmissiveMap,s.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uNormalMap&&r&&(this._program.bindTexture(this._uNormalMap,r.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o),this._uAOMap&&n&&(this._program.bindTexture(this._uAOMap,n.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o)}if(p.reflectionMaps.length>0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;ts[0]=i,ts[1]=s,ts[2]=t.blendCutoff,ts[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,ts),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(this._useAlphaCutoff&&a.uniform1f(this._alphaCutoffLocation,c.alphaCutoff),s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===qi[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===qi[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===qi[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?es:$i)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class ns extends os{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!1,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)i.edgeIndicesBuf&&t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class as extends ns{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.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;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));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("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),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;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),o.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?(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(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class ls extends ns{_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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading 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;")),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("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";");r.push("uniform float sliceThickness;"),r.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(r),r.push("uniform vec4 lightAmbient;");for(let e=0,i=t.lights.length;e<i;e++){const i=t.lights[e];"ambient"!==i.type&&(r.push("uniform vec4 lightColor"+e+";"),"dir"===i.type&&r.push("uniform vec3 lightDir"+e+";"),"point"===i.type&&r.push("uniform vec3 lightPos"+e+";"),"spot"===i.type&&(r.push("uniform vec3 lightPos"+e+";"),r.push("uniform vec3 lightDir"+e+";")))}if(r.push("in vec4 vViewPosition;"),r.push("in vec4 vColor;"),r.push("out vec4 outColor;"),r.push("void main(void) {"),r.push(" vec4 newColor;"),r.push(" newColor = vColor;"),s){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();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 > sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}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 ) );");for(let e=0,i=t.lights.length;e<i;e++){const i=t.lights[e];if("ambient"!==i.type){if("dir"===i.type)"view"===i.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===i.type)"view"===i.space?r.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):r.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==i.type)continue;"view"===i.space?r.push("viewLightDir = normalize(lightDir"+e+");"):r.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}r.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),r.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return r.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.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(" float dx = dFdx(gl_FragCoord.z);"),r.push(" float dy = dFdy(gl_FragCoord.z);"),r.push(" float diff = sqrt(dx*dx+dy*dy);"),r.push(" gl_FragDepth = gl_FragCoord.z + diff;")),r.push("}"),r}}class As extends ns{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");o.push("uniform float sliceThickness;"),o.push("uniform vec4 sliceColor;")}if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),o.push(" vec4 newColor;"),o.push(" newColor = vColor;"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class cs extends ns{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class hs extends cs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class us extends cs{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.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);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ds extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class ps extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class fs extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.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("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),s.push("}"),s}}class ms extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching 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){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push(" if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class gs extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec2 vHighPrecisionZW;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class _s extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.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("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class vs extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry 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"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),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(v * bitShift);"),i.push(" comp -= comp.xxyz * bitMask;"),i.push(" return comp;"),i.push("}"),i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".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}}class bs extends ns{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.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;")),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 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality 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;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(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("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.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 );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),o&&n.push("in vec4 vClipPosition;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";")}if(n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.x == 0.0 && texel.y == 0.0 && texel.z == 0.0) {"),n.push(" return surf_norm;"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;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("}");o?(n.push(" if (dist > (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");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?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),n.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return n.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),n.push("float aoFactor = texture(uAOMap, vUV).r;"),n.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),n.push("vec4 fragColor;"),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(" fragColor = vec4(outgoingLight.rgb * ambient * aoFactor, opacity);")):n.push(" fragColor = vec4(outgoingLight.rgb * aoFactor, opacity);"),t&&n.push("fragColor = linearToGamma(fragColor, gammaFactor);"),n.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class ys extends ns{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.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("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),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("}"),s}}class ws extends ns{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture 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 sampler2D uColorMap;"),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("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.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 );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(o&&n.push("uniform float materialAlphaCutoff;"),n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;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 > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return n.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),n.push("vec4 sampleColor = texture(uColorMap, vUV);"),o&&(n.push("if (sampleColor.a < materialAlphaCutoff) {"),n.push(" discard;"),n.push("}")),t&&n.push("sampleColor = sRGBToLinear(sampleColor);"),n.push("vec4 colorTexel = color * sampleColor;"),n.push("float opacity = color.a;"),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(colorTexel.rgb * ambient, opacity);")):n.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&n.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}const Bs=h.vec3(),xs=h.vec3(),Ps=h.vec3(),Cs=h.vec3(),Ms=h.mat4();class Fs extends os{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Bs;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=xs;if(l){const e=Ps;h.transformPoint3(c,l,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]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Ms),m=Cs,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),n.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Es=h.vec3(),Is=h.vec3(),Ts=h.vec3(),Ds=h.vec3(),Ss=h.mat4();class Rs extends os{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Es;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Is;if(l){const e=Ts;h.transformPoint3(c,l,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]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Ss),m=Ds,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Us{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._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=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),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new As(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ds(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new ps(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Fs(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Rs(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new as(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new as(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new ls(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new ls(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ws(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ws(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new ws(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new ws(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new bs(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new bs(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new As(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new gs(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new _s(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new hs(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new us(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ds(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new fs(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new ys(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ps(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ms(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new vs(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Rs(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Fs(this._scene)),this._snapInitRenderer}_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._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.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(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ls={};let ks=65536,Os=5e6;class Ns{constructor(){}set doublePrecisionEnabled(e){h.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return h.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),ks=e}get maxDataTextureHeight(){return ks}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Os=e}get maxGeometryBatchSize(){return Os}}const Vs=new Ns;class Qs{constructor(e=Vs.maxGeometryBatchSize){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 Hs=h.mat4(),Gs=h.mat4();function js(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,c=t[5]-a,u=65525,d=u/l,p=u/A,f=u/c,m=e=>e>=0?e:0;for(let t=0;t<s;t+=3)r[t+0]=Math.floor(m(e[t+0]-o)*d),r[t+1]=Math.floor(m(e[t+1]-n)*p),r[t+2]=Math.floor(m(e[t+2]-a)*f);return h.identityMat4(Hs),h.translationMat4v(t,Hs),h.identityMat4(Gs),h.scalingMat4v([l/u,A/u,c/u],Gs),h.mulMat4(Hs,Gs,i),r}function zs(e,t){const i=e[0],s=e[1],r=e[2],o=e[3]-i,n=e[4]-s,a=e[5]-r,l=65525;return h.identityMat4(Hs),h.translationMat4v(e,Hs),h.identityMat4(Gs),h.scalingMat4v([o/l,n/l,a/l],Gs),h.mulMat4(Hs,Gs,t),t}function Ws(e,t,i){let s=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),r=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=s,t=r;e=(1-Math.abs(r))*(s>=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function Xs(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Ks=h.mat4(),Zs=h.mat4(),Js=h.vec4([0,0,0,1]),Ys=h.vec3(),qs=h.vec3(),$s=h.vec3(),er=h.vec3(),tr=h.vec3(),ir=h.vec3(),sr=h.vec3();class rr{constructor(e){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._renderers=function(e){const t=e.id;let i=Ls[t];return i||(i=new Us(e),Ls[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Ls[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Qs(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new ie({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._meshes=[],this._numVerts=0,this._aabb=h.collapseAABB3(),this.aabbDirty=!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.solid=!!e.solid,this.primitive=e.primitive}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}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,t){if(this._finalized)throw"Already finalized";const i=t.positions,s=t.positionsCompressed,r=t.normals,o=t.normalsCompressed,n=t.uv,a=t.uvCompressed,l=t.colors,A=t.colorsCompressed,c=t.indices,u=t.edgeIndices,d=t.color,p=t.metallic,f=t.roughness,m=t.opacity,g=t.meshMatrix,_=t.pickColor,v=this.model.scene,b=this._buffer,y=b.positions.length/3;let w;if(h.expandAABB3(this._modelAABB,t.aabb),this._state.positionsDecodeMatrix){if(!s)throw"positionsCompressed expected";w=s.length/3;for(let e=0,t=s.length;e<t;e++)b.positions.push(s[e])}else{if(!i)throw"positions expected";w=i.length/3;for(let e=0,t=i.length;e<t;e++)b.positions.push(i[e])}if(o&&o.length>0)for(let e=0,t=o.length;e<t;e++)b.normals.push(o[e]);else if(r&&r.length>0){const e=Ks;g?h.inverseMat4(h.transposeMat4(g,Zs),e):h.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,c,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;u<i;u+=3)d[0]=t[u],d[1]=t[u+1],d[2]=t[u+2],h.transformVec3(e,d,p),h.normalizeVec3(p,p),l=n=Ws(p,"floor","floor"),a=Xs(n),A=c=o(p,a),n=Ws(p,"ceil","floor"),a=Xs(n),A=o(p,a),A>c&&(l=n,c=A),n=Ws(p,"floor","ceil"),a=Xs(n),A=o(p,a),A>c&&(l=n,c=A),n=Ws(p,"ceil","ceil"),a=Xs(n),A=o(p,a),A>c&&(l=n,c=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)b.colors.push(255*l[e]),b.colors.push(255*l[e+1]),b.colors.push(255*l[e+2]),b.colors.push(255);else if(A)for(let e=0,t=l.length;e<t;e+=3)b.colors.push(l[e]),b.colors.push(l[e+1]),b.colors.push(l[e+2]),b.colors.push(255);else if(d){const e=d[0],t=d[1],i=d[2],s=m;for(let r=0;r<w;r++)b.colors.push(e),b.colors.push(t),b.colors.push(i),b.colors.push(s)}const B=null!=p?p:0,x=null!=f?f:255;for(let e=0;e<w;e++)b.metallicRoughness.push(B),b.metallicRoughness.push(x);if(n&&n.length>0)for(let e=0,t=n.length;e<t;e++)b.uv.push(n[e]);else if(a&&a.length>0)for(let e=0,t=a.length;e<t;e++)b.uv.push(a[e]);for(let e=0,t=c.length;e<t;e++)b.indices.push(y+c[e]);if(u)for(let e=0,t=u.length;e<t;e++)b.edgeIndices.push(y+u[e]);{const e=b.pickColors.length;for(let t=e,i=e+4*w;t<i;t+=4)b.pickColors.push(_[0]),b.pickColors.push(_[1]),b.pickColors.push(_[2]),b.pickColors.push(_[3])}if(v.entityOffsetsEnabled)for(let e=0;e<w;e++)b.offsets.push(0),b.offsets.push(0),b.offsets.push(0);const P=this._portions.length,C={vertsBaseIndex:y,numVerts:w,indicesBaseIndex:b.indices.length-c.length,numIndices:c.length};return v.readableGeometryEnabled&&(C.indices=c,v.entityOffsetsEnabled&&(C.offset=new Float32Array(3))),this._portions.push(C),this._numPortions++,this.model.numPortions++,this._numVerts+=C.numVerts,this._meshes.push(e),P}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):js(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=h.mat4());if(e.positionsBuf=new se(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.readableGeometryEnabled)for(let e=0,t=this._portions.length;e<t;e++){const t=this._portions[e],i=3*t.vertsBaseIndex,r=i+3*t.numVerts;t.quantizedPositions=s.slice(i,r)}}if(i.normals.length>0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new se(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new se(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new se(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=he.getUVBounds(i.uv),r=he.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=h.mat3(r.decodeMatrix),e.uvBuf=new se(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new se(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new se(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new se(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new se(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,s,i.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,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],c=t[3];for(let e=0;e<o;e+=4)n[e+0]=a,n[e+1]=l,n[e+2]=A,n[e+3]=c;this._state.colorsBuf&&this._state.colorsBuf.setData(n,r,o)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=e,o=this._portions[r],n=o.vertsBaseIndex,a=o.numVerts,l=!!(t&Gi),A=!!(t&Ki),c=!!(t&Zi),h=!!(t&Ji),u=!!(t&Yi),d=!!(t&zi),p=!!(t&ji);let f,m;f=!l||p||A||c&&!this.model.scene.highlightMaterial.glowThrough||h&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,m=!l||p?qi.NOT_RENDERED:h?qi.SILHOUETTE_SELECTED:c?qi.SILHOUETTE_HIGHLIGHTED:A?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let g=0;g=!l||p?qi.NOT_RENDERED:h?qi.EDGES_SELECTED:c?qi.EDGES_HIGHLIGHTED:A?qi.EDGES_XRAYED:u?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let _=l&&!p&&d?qi.PICK:qi.NOT_RENDERED;const v=t&Wi?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=n,t=n+a;e<t;e++){let t=0;t|=f,t|=m<<4,t|=g<<8,t|=_<<12,t|=v<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(a);for(let t=0;t<a;t++){let i=0;i|=f,i|=m<<4,i|=g<<8,i|=_<<12,i|=v<<16,e[t]=i}this._state.flagsBuf.setData(e,n,a)}}_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 i=e,s=this._portions[i],r=3*s.vertsBaseIndex,o=3*s.numVerts,n=this._scratchMemory.getFloat32Array(o),a=t[0],l=t[1],A=t[2];for(let e=0;e<o;e+=3)n[e+0]=a,n[e+1]=l,n[e+2]=A;this._state.offsetsBuf&&this._state.offsetsBuf.setData(n,r,o),this.model.scene.readableGeometryEnabled&&(s.offset[0]=t[0],s.offset[1]=t[1],s.offset[2]=t[2])}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portions[e];if(!s)return void this.model.error("portion not found: "+e);const r=s.quantizedPositions,o=this.model.matrix,n=h.vec4();n.set(i.origin,0),n[3]=1,h.mulMat4v4(o,n,n);const a=n[0],l=n[1],A=n[2],c=Js,u=i.positionsDecodeMatrix;for(let e=0,i=r.length;e<i;e+=3)c[0]=r[e],c[1]=r[e+1],c[2]=r[e+2],c[3]=1,h.decompressPosition(c,u),c[3]=1,h.mulMat4v4(o,c,c),c[0]+=a,c[1]+=l,c[2]+=A,t(c)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._portions[e];if(!i)return void this.model.error("portion not found: "+e);const s=i.indices;for(let e=0,i=s.length;e<i;e++)t(s[e])}getElementsCountAndOffset(e){let t=null,i=null;const s=this._portions[e];return s&&(t=s.numIndices,i=s.indicesBaseIndex),{count:t,offset:i}}readGeometryData(e){if(!this._finalized)throw"Not finalized";const t=this._portions[e],i=this._state,s=this.model.matrix,r=i.positionsDecodeMatrix,o=h.vec4();o.set(i.origin,0),o[3]=1,h.mulMat4v4(s,o,o);const n=i.indicesBuf.getData(t.indicesBaseIndex,t.numIndices).map((e=>e-t.vertsBaseIndex)),a=h.mulMat4(s,r,new Array(16));a[12]+=o[0],a[13]+=o[1],a[14]+=o[2];const l=i.positionsBuf.getData(t.vertsBaseIndex,t.numVerts);return{indices:n,positions:h.transformPositions3(a,l,new Array(l.length))}}drawColorOpaque(e,t){if(this._numCulledLayerPortions===this._numPortions||0===this._numVisibleLayerPortions||this._numTransparentLayerPortions===this._numPortions||this._numXRayedLayerPortions===this._numPortions)return;this._updateBackfaceCull(e,t);const i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){if(this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions)if(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported)this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT);else if(t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported){this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}else this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.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._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,qi.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._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,qi.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK))}precisionRayPickSurface(e,t,i,s,r){if(!this.model.scene.readableGeometryEnabled)return!1;const o=this._state,n=this._portions[e];if(!n)return this.model.error("portion not found: "+e),!1;const a=n.quantizedPositions,l=n.indices,A=o.origin,c=n.offset,u=Ys,d=qs;u.set(A?h.subVec3(t,A,$s):t),d.set(i),c&&h.subVec3(u,c),h.transformRay(this.model.worldNormalMatrix,u,d,u,d);const p=er,f=tr,m=ir;let g=!1,_=0;const v=sr;for(let e=0,i=l.length;e<i;e+=3){const i=3*l[e],n=3*l[e+1],b=3*l[e+2];if(p[0]=a[i],p[1]=a[i+1],p[2]=a[i+2],f[0]=a[n],f[1]=a[n+1],f[2]=a[n+2],m[0]=a[b],m[1]=a[b+1],m[2]=a[b+2],h.decompressPosition(p,o.positionsDecodeMatrix),h.decompressPosition(f,o.positionsDecodeMatrix),h.decompressPosition(m,o.positionsDecodeMatrix),h.rayTriangleIntersect(u,d,p,f,m,v)){h.transformPoint3(this.model.worldMatrix,v,v),c&&h.addVec3(v,c),A&&h.addVec3(v,A);const e=Math.abs(h.lenVec3(h.subVec3(v,t,[])));(!g||e>_)&&(_=e,s.set(v),r&&h.triangleNormal(p,f,m,r),g=!0)}}return g&&r&&(h.transformVec3(this.model.worldNormalMatrix,r,r),h.normalizeVec3(r)),g}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 or extends os{constructor(e,t,{edges:i=!1,useAlphaCutoff:s=!1}={}){super(e,t,{instancing:!0,edges:i,useAlphaCutoff:s})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?i.edgeIndicesBuf&&t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class nr extends or{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),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),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;"),r=0,o=i.lights.length;r<o;r++)n=i.lights[r],"ambient"!==n.type&&(a.push("uniform vec4 lightColor"+r+";"),"dir"===n.type&&a.push("uniform vec3 lightDir"+r+";"),"point"===n.type&&a.push("uniform vec3 lightPos"+r+";"),"spot"===n.type&&(a.push("uniform vec3 lightPos"+r+";"),a.push("uniform vec3 lightDir"+r+";")));for(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("}"),s&&(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 = 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), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(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;"),r=0,o=i.lights.length;r<o;r++)if(n=i.lights[r],"ambient"!==n.type){if("dir"===n.type)"view"===n.space?a.push("viewLightDir = normalize(lightDir"+r+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);");else if("point"===n.type)"view"===n.space?a.push("viewLightDir = -normalize(lightPos"+r+" - viewPosition.xyz);"):a.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+r+", 0.0)).xyz);");else{if("spot"!==n.type)continue;"view"===n.space?a.push("viewLightDir = normalize(lightDir"+r+");"):a.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);")}a.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),a.push("reflectedColor += lambertian * (lightColor"+r+".rgb * lightColor"+r+".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));")),s&&(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,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?(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(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class ar extends or{_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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading 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("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}for(this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;"),s=0,r=i.lights.length;s<r;s++){const e=i.lights[s];"ambient"!==e.type&&(n.push("uniform vec4 lightColor"+s+";"),"dir"===e.type&&n.push("uniform vec3 lightDir"+s+";"),"point"===e.type&&n.push("uniform vec3 lightPos"+s+";"),"spot"===e.type&&(n.push("uniform vec3 lightPos"+s+";"),n.push("uniform vec3 lightDir"+s+";")))}if(n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),o){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;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 > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s<r;s++){const e=i.lights[s];if("ambient"!==e.type){if("dir"===e.type)"view"===e.space?n.push("viewLightDir = normalize(lightDir"+s+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+s+", 0.0)).xyz);");else if("point"===e.type)"view"===e.space?n.push("viewLightDir = -normalize(lightPos"+s+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+s+", 0.0)).xyz);");else{if("spot"!==e.type)continue;"view"===e.space?n.push("viewLightDir = normalize(lightDir"+s+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+s+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+s+".rgb * lightColor"+s+".a);")}}return n.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),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(fragColor.rgb * ambient, 1.0);")):n.push(" outColor = fragColor;"),e.logarithmicDepthBufferEnabled?n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(n.push(" float dx = dFdx(gl_FragCoord.z);"),n.push(" float dy = dFdy(gl_FragCoord.z);"),n.push(" float diff = sqrt(dx*dx+dy*dy);"),n.push(" gl_FragDepth = gl_FragCoord.z + diff;")),n.push("}"),n}}class lr extends or{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class Ar extends or{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class cr extends Ar{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class hr extends Ar{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.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);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ur extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class dr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class pr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.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("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vWorldNormal;"),s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${h.MAX_INT}), 1.0);`),s.push("}"),s}}class fr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer 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){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class mr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("in vec2 vHighPrecisionZW;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class gr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.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("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class _r extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const vr={3e3:"linearToLinear",3001:"sRGBToLinear"};class br extends or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.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;")),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 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality 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;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),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.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.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 );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),o&&n.push("in vec4 vClipPosition;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;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("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+vr[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+vr[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e<t;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("}");o?(n.push(" if (dist > (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");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?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("light.direction = normalize(lightDir"+e+");"):n.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("light.color = lightColor"+e+".rgb * lightColor"+e+".a;"),n.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return n.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;"),n.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;"),n.push("vec4 fragColor;"),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(" fragColor = vec4(outgoingLight.rgb * ambient, opacity);")):n.push(" fragColor = vec4(outgoingLight.rgb, opacity);"),t&&n.push("fragColor = linearToGamma(fragColor, gammaFactor);"),n.push("outColor = fragColor;"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}class yr extends or{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.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;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out highp ivec4 outNormal;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),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("}"),s}}class wr extends or{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=this._useAlphaCutoff,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;")),n.push("uniform sampler2D uColorMap;"),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("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.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 );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;e++)n.push("uniform bool sectionPlaneActive"+e+";"),n.push("uniform vec3 sectionPlanePos"+e+";"),n.push("uniform vec3 sectionPlaneDir"+e+";");n.push("uniform float sliceThickness;"),n.push("uniform vec4 sliceColor;")}this._addMatricesUniformBlockLines(n),n.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(n.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&n.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&n.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(n.push("uniform vec3 lightPos"+e+";"),n.push("uniform vec3 lightDir"+e+";")))}if(o&&n.push("uniform float materialAlphaCutoff;"),n.push("in vec4 vViewPosition;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("out vec4 outColor;"),n.push("void main(void) {"),n.push(" vec4 newColor;"),n.push(" newColor = vColor;"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e<t;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 > sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?n.push("viewLightDir = -normalize(lightPos"+e+" - vViewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?n.push("viewLightDir = normalize(lightDir"+e+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return n.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);"),n.push("vec4 sampleColor = texture(uColorMap, vUV);"),o&&(n.push("if (sampleColor.a < materialAlphaCutoff) {"),n.push(" discard;"),n.push("}")),t&&n.push("sampleColor = sRGBToLinear(sampleColor);"),n.push("vec4 colorTexel = color * sampleColor;"),n.push("float opacity = color.a;"),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(colorTexel.rgb * ambient, opacity);")):n.push(" outColor = vec4(colorTexel.rgb, opacity);"),t&&n.push("outColor = linearToGamma(outColor, gammaFactor);"),e.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}const Br=h.vec3(),xr=h.vec3(),Pr=h.vec3(),Cr=h.vec3(),Mr=h.mat4();class Fr extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Br;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=xr;if(l){const e=h.transformPoint3(c,l,Pr);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Mr),m=Cr,m[0]=n.eye[0]-t[0],m[1]=n.eye[1]-t[1],m[2]=n.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,m),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElementsInstanced(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Er=h.vec3(),Ir=h.vec3(),Tr=h.vec3(),Dr=h.vec3(),Sr=h.mat4();class Rr extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Er;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ir;if(l){const e=h.transformPoint3(c,l,Tr);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Sr),m=Dr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?a.edgeIndicesBuf&&(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ur{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._colorTextureRendererAlphaCutoff&&!this._colorTextureRendererAlphaCutoff.getValid()&&(this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererAlphaCutoff=null),this._colorTextureRendererWithSAOAlphaCutoff&&!this._colorTextureRendererWithSAOAlphaCutoff.getValid()&&(this._colorTextureRendererWithSAOAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff=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),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new lr(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new ur(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new dr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Fr(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Rr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new nr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new nr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new ar(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new ar(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new wr(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new wr(this._scene,!0)),this._colorTextureRendererWithSAO}get colorTextureRendererAlphaCutoff(){return this._colorTextureRendererAlphaCutoff||(this._colorTextureRendererAlphaCutoff=new wr(this._scene,!1,{useAlphaCutoff:!0})),this._colorTextureRendererAlphaCutoff}get colorTextureRendererWithSAOAlphaCutoff(){return this._colorTextureRendererWithSAOAlphaCutoff||(this._colorTextureRendererWithSAOAlphaCutoff=new wr(this._scene,!0,{useAlphaCutoff:!0})),this._colorTextureRendererWithSAOAlphaCutoff}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new br(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new br(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new lr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new mr(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new gr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new cr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new hr(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ur(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new pr(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new yr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new dr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new fr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new _r(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Rr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Fr(this._scene)),this._snapInitRenderer}_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._colorTextureRendererAlphaCutoff&&this._colorTextureRendererAlphaCutoff.destroy(),this._colorTextureRendererWithSAOAlphaCutoff&&this._colorTextureRendererWithSAOAlphaCutoff.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(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Lr={};const kr=new Uint8Array(4),Or=new Float32Array(1),Nr=h.vec4([0,0,0,1]),Vr=new Float32Array(3),Qr=h.vec3(),Hr=h.vec3(),Gr=h.vec3(),jr=h.vec3(),zr=h.vec3(),Wr=h.vec3(),Xr=h.vec3(),Kr=new Float32Array(4);class Zr{constructor(e){this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Lr[t];return i||(i=new Ur(e),Lr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Lr[t],i._destroy()}))),i}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new ie({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=[],this._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices,this.primitive=e.geometry.primitive}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}createPortion(e,t){const i=t.color,s=t.metallic,r=t.roughness,o=null!==t.opacity&&void 0!==t.opacity?t.opacity:255,n=t.meshMatrix,a=t.pickColor;if(this._finalized)throw"Already finalized";const l=i[0],A=i[1],c=i[2];if(this._colors.push(l),this._colors.push(A),this._colors.push(c),this._colors.push(o),this._metallicRoughness.push(null!=s?s:0),this._metallicRoughness.push(null!=r?r:255),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]),this._state.geometry.normals){let e=h.transposeMat4(n,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(a[0]),this._pickColors.push(a[1]),this._pickColors.push(a[2]),this._pickColors.push(a[3]),this._state.numInstances++;const u=this._portions.length,d={};return this.model.scene.readableGeometryEnabled&&(d.matrix=n.slice(),d.inverseMatrix=null,d.normalMatrix=null),this._portions.push(d),this._numPortions++,this.model.numPortions++,this._meshes.push(e),u}finalize(){if(this._finalized)return;const e=this._state,t=e.geometry,i=e.textureSet,s=this.model.scene.canvas.gl,r=this._colors.length,o=r/4;if(r>0){let t=!1;e.colorsBuf=new se(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new se(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new se(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new se(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=h.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new se(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new se(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),t.edgeIndices&&t.edgeIndices.length>0&&(e.edgeIndicesBuf=new se(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new se(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new se(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(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,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";kr[0]=t[0],kr[1]=t[1],kr[2]=t[2],kr[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(kr,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Gi),r=!!(t&Ki),o=!!(t&Zi),n=!!(t&Ji),a=!!(t&Yi),l=!!(t&zi),A=!!(t&ji);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,h=!s||A?qi.NOT_RENDERED:n?qi.SILHOUETTE_SELECTED:o?qi.SILHOUETTE_HIGHLIGHTED:r?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let u=0;u=!s||A?qi.NOT_RENDERED:n?qi.EDGES_SELECTED:o?qi.EDGES_HIGHLIGHTED:r?qi.EDGES_XRAYED:a?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?qi.PICK:qi.NOT_RENDERED)<<12,d|=(t&Wi?1:0)<<16,Or[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Or,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Vr[0]=t[0],Vr[1]=t[1],Vr[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Vr,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.positionsCompressed,n=this.model.matrix,a=h.vec4();a.set(i.origin,0),a[3]=1,h.mulMat4v4(n,a,a);const l=a[0],A=a[1],c=a[2],u=Nr,d=r.matrix,p=i.positionsDecodeMatrix;for(let e=0,i=o.length;e<i;e+=3)u[0]=o[e],u[1]=o[e+1],u[2]=o[e+2],h.decompressPosition(u,p),h.transformPoint3(d,u,u),u[3]=1,h.mulMat4v4(n,u,u),u[0]+=l,u[1]+=A,u[2]+=c,t(u)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return!1;const i=this._state.geometry;if(!this._portions[e])return void this.model.error("portion not found: "+e);const s=i.indices;for(let e=0,i=s.length;e<i;e++)t(s[e])}setMatrix(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Kr[0]=t[0],Kr[1]=t[4],Kr[2]=t[8],Kr[3]=t[12],this._state.modelMatrixCol0Buf.setData(Kr,i),Kr[0]=t[1],Kr[1]=t[5],Kr[2]=t[9],Kr[3]=t[13],this._state.modelMatrixCol1Buf.setData(Kr,i),Kr[0]=t[2],Kr[1]=t[6],Kr[2]=t[10],Kr[3]=t[14],this._state.modelMatrixCol2Buf.setData(Kr,i)}readGeometryData(e){if(!this._finalized)throw"Not finalized";const t=this._state,i=this.model.matrix,s=t.modelMatrixCol0Buf.getData(e,1),r=t.modelMatrixCol1Buf.getData(e,1),o=t.modelMatrixCol2Buf.getData(e,1),n=[s[0],r[0],o[0],0,s[1],r[1],o[1],0,s[2],r[2],o[2],0,s[3],r[3],o[3],1],a=t.positionsDecodeMatrix,l=h.vec4();l.set(t.origin,0),l[3]=1,h.mulMat4v4(i,l,l);const A=t.indicesBuf.getData(),c=h.mulMat4(n,a,new Array(16));h.mulMat4(i,c,c),c[12]+=l[0],c[13]+=l[1],c[14]+=l[2];const u=t.positionsBuf.getData();return{indices:A,positions:h.transformPositions3(c,u,new Array(u.length))}}drawColorOpaque(e,t){if(this._numCulledLayerPortions===this._numPortions||0===this._numVisibleLayerPortions||this._numTransparentLayerPortions===this._numPortions||this._numXRayedLayerPortions===this._numPortions)return;this._updateBackfaceCull(e,t);const i=this._state.textureSet&&"number"==typeof this._state.textureSet.alphaCutoff;t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRendererWithSAO&&this._renderers.pbrRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererWithSAOAlphaCutoff&&this._renderers.colorTextureRendererWithSAOAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRendererWithSAO&&this._renderers.colorTextureRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRendererWithSAO&&this._renderers.flatColorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):t.pbrEnabled&&this.model.pbrEnabled&&this._state.pbrSupported?this._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?i?this._renderers.colorTextureRendererAlphaCutoff&&this._renderers.colorTextureRendererAlphaCutoff.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}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._renderers.pbrRenderer&&this._renderers.pbrRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):t.colorTextureEnabled&&this.model.colorTextureEnabled&&this._state.colorTextureSupported?this._renderers.colorTextureRenderer&&this._renderers.colorTextureRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._state.normalsBuf?this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT):this._renderers.flatColorRenderer&&this._renderers.flatColorRenderer.drawLayer(t,this,qi.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._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,qi.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._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_TRANSPARENT)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_XRAYED)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_SELECTED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsFlatRenderer&&this._renderers.pickNormalsFlatRenderer.drawLayer(t,this,qi.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK))}precisionRayPickSurface(e,t,i,s,r){if(!this.model.scene.readableGeometryEnabled)return!1;const o=this._state.geometry,n=this._state,a=this._portions[e];if(!a)return this.model.error("portion not found: "+e),!1;a.inverseMatrix||(a.inverseMatrix=h.inverseMat4(a.matrix,h.mat4())),r&&!a.normalMatrix&&(a.normalMatrix=h.transposeMat4(a.inverseMatrix,h.mat4()));const l=o.quantizedPositions,A=o.indices,c=n.origin,u=a.offset,d=Qr,p=Hr;d.set(c?h.subVec3(t,c,Gr):t),p.set(i),u&&h.subVec3(d,u),h.transformRay(this.model.worldNormalMatrix,d,p,d,p),h.transformRay(a.inverseMatrix,d,p,d,p);const f=jr,m=zr,g=Wr;let _=!1,v=0;const b=Xr;for(let e=0,i=A.length;e<i;e+=3){const i=3*A[e+0],o=3*A[e+1],y=3*A[e+2];f[0]=l[i],f[1]=l[i+1],f[2]=l[i+2],m[0]=l[o],m[1]=l[o+1],m[2]=l[o+2],g[0]=l[y],g[1]=l[y+1],g[2]=l[y+2];const{positionsDecodeMatrix:w}=n.geometry;if(h.decompressPosition(f,w),h.decompressPosition(m,w),h.decompressPosition(g,w),h.rayTriangleIntersect(d,p,f,m,g,b)){h.transformPoint3(a.matrix,b,b),h.transformPoint3(this.model.worldMatrix,b,b),u&&h.addVec3(b,u),c&&h.addVec3(b,c);const e=Math.abs(h.lenVec3(h.subVec3(b,t,[])));(!_||e>v)&&(v=e,s.set(b),r&&h.triangleNormal(f,m,g,r),_=!0)}}return _&&r&&(h.transformVec3(a.normalMatrix,r,r),h.transformVec3(this.model.worldNormalMatrix,r,r),h.normalizeVec3(r)),_}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 Jr extends os{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class Yr extends Jr{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class qr extends Jr{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const $r=h.vec3(),eo=h.vec3(),to=h.vec3(),io=h.vec3(),so=h.mat4();class ro extends os{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=$r;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=eo;if(l){const e=to;h.transformPoint3(c,l,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]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,so),m=io,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind(),n.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const oo=h.vec3(),no=h.vec3(),ao=h.vec3(),lo=h.vec3(),Ao=h.mat4();class co extends os{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=oo;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=no;if(l){const e=ao;h.transformPoint3(c,l,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]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Ao),m=lo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ho{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._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ro(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new co(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const uo={};class po{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class fo{constructor(e){this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=uo[t];return i||(i=new ho(e),uo[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete uo[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new po(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new ie({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._meshes=[],this._numVerts=0,this._aabb=h.collapseAABB3(),this.aabbDirty=!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.primitive=e.primitive}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}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,t){if(this._finalized)throw"Already finalized";const i=t.positions,s=t.positionsCompressed,r=t.indices,o=t.color,n=t.opacity,a=this._buffer,l=a.positions.length/3;let A;if(h.expandAABB3(this._modelAABB,t.aabb),this._preCompressedPositionsExpected){if(!s)throw"positionsCompressed expected";A=s.length/3;for(let e=0,t=s.length;e<t;e++)a.positions.push(s[e])}else{if(!i)throw"positions expected";A=i.length/3;for(let e=0,t=i.length;e<t;e++)a.positions.push(i[e])}if(o){const e=o[0],t=o[1],i=o[2],s=n;for(let r=0;r<A;r++)a.colors.push(e),a.colors.push(t),a.colors.push(i),a.colors.push(s)}if(r)for(let e=0,t=r.length;e<t;e++)a.indices.push(r[e]+l);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<A;e++)a.offsets.push(0),a.offsets.push(0),a.offsets.push(0);const c=this._portions.length/2;return this._portions.push(l),this._portions.push(A),this._numPortions++,this.model.numPortions++,this._numVerts+=A,this._meshes.push(e),c}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new se(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=js(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new se(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new se(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new se(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new se(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new se(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e<r;e+=4)o[e+0]=n,o[e+1]=a,o[e+2]=l,o[e+3]=A;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=2*e,o=this._portions[r],n=this._portions[r+1],a=!!(t&Gi),l=!!(t&Ki),A=!!(t&Zi),c=!!(t&Ji),h=!!(t&zi),u=!!(t&ji);let d,p;d=!a||u||l||A&&!this.model.scene.highlightMaterial.glowThrough||c&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,p=!a||u?qi.NOT_RENDERED:c?qi.SILHOUETTE_SELECTED:A?qi.SILHOUETTE_HIGHLIGHTED:l?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let f=a&&!u&&h?qi.PICK:qi.NOT_RENDERED;const m=t&Wi?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(let e=o,t=o+n;e<t;e++){let t=0;t|=d,t|=p<<4,t|=f<<12,t|=m<<16,this._deferredFlagValues[e]=t}}else if(this._state.flagsBuf){const e=this._scratchMemory.getFloat32Array(n);for(let t=0;t<n;t++){let i=0;i|=d,i|=p<<4,i|=f<<12,i|=m<<16,e[t]=i}this._state.flagsBuf.setData(e,o,n)}}_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 i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}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 mo extends os{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElementsInstanced(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++}}class go extends mo{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("in vec4 vColor;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class _o extends mo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const vo=h.vec3(),bo=h.vec3(),yo=h.vec3();h.vec3();const wo=h.mat4();class Bo extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=vo;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=bo;if(l){const e=h.transformPoint3(c,l,yo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,wo),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xo=h.vec3(),Po=h.vec3(),Co=h.vec3();h.vec3();const Mo=h.mat4();class Fo extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=xo;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Po;if(l){const e=h.transformPoint3(c,l,Co);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Mo),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(2.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Eo{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._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Bo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Fo(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new go(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new _o(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Bo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Fo(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Io={};const To=new Uint8Array(4),Do=new Float32Array(1),So=new Float32Array(3),Ro=new Float32Array(4);class Uo{constructor(e){this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Io[t];return i||(i=new Eo(e),Io[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Io[t],i._destroy()}))),i}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new ie({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=[],this._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=h.vec3(e.origin)),this._finalized=!1,this.primitive=e.primitive}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}createPortion(e,t){const i=t.color,s=t.opacity,r=t.meshMatrix;if(this._finalized)throw"Already finalized";const o=i[0],n=i[1],a=i[2];i[3],this._colors.push(o),this._colors.push(n),this._colors.push(a),this._colors.push(s),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(r[0]),this._modelMatrixCol0.push(r[4]),this._modelMatrixCol0.push(r[8]),this._modelMatrixCol0.push(r[12]),this._modelMatrixCol1.push(r[1]),this._modelMatrixCol1.push(r[5]),this._modelMatrixCol1.push(r[9]),this._modelMatrixCol1.push(r[13]),this._modelMatrixCol2.push(r[2]),this._modelMatrixCol2.push(r[6]),this._modelMatrixCol2.push(r[10]),this._modelMatrixCol2.push(r[14]),this._state.numInstances++;const l=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),l}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._state,i=t.geometry,s=this._colors.length,r=s/4;if(s>0){let t=!1;this._state.colorsBuf=new se(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new se(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new se(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=h.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new se(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this.model.scene.readableGeometryEnabled||(this._state.geometry=null),this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(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,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";To[0]=t[0],To[1]=t[1],To[2]=t[2],To[3]=t[3],this._state.colorsBuf.setData(To,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Gi),r=!!(t&Ki),o=!!(t&Zi),n=!!(t&Ji),a=!!(t&Yi),l=!!(t&zi),A=!!(t&ji);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,h=!s||A?qi.NOT_RENDERED:n?qi.SILHOUETTE_SELECTED:o?qi.SILHOUETTE_HIGHLIGHTED:r?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let u=0;u=!s||A?qi.NOT_RENDERED:n?qi.EDGES_SELECTED:o?qi.EDGES_HIGHLIGHTED:r?qi.EDGES_XRAYED:a?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?qi.PICK:qi.NOT_RENDERED)<<12,d|=(t&Wi?1:0)<<16,Do[0]=d,this._state.flagsBuf.setData(Do,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(So[0]=t[0],So[1]=t[1],So[2]=t[2],this._state.offsetsBuf.setData(So,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Ro[0]=t[0],Ro[1]=t[4],Ro[2]=t[8],Ro[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ro,i),Ro[0]=t[1],Ro[1]=t[5],Ro[2]=t[9],Ro[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ro,i),Ro[0]=t[2],Ro[1]=t[6],Ro[2]=t[10],Ro[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ro,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}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 Lo extends os{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class ko extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points 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),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),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 {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Oo extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points 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;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("uniform vec4 color;"),o.push("out vec4 outColor;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push(" float r = dot(cxy, cxy);"),o.push(" if (r > 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push(" if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class No extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh 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),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Vo extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched 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),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r<t.getNumAllocatedSectionPlanes();r++)s.push(" if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Qo extends Lo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion 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 float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push(" if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push(" }");s.push(" if (dist > 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const Ho=h.vec3(),Go=h.vec3(),jo=h.vec3(),zo=h.vec3(),Wo=h.mat4();class Xo extends os{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Ho;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Go;if(l){const e=jo;h.transformPoint3(c,l,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]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,Wo),m=zo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform1f(this._uPointSize,1);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_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"),this._uPointSize=e.getLocation("pointSize")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float pointSize;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = pointSize;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ko=h.vec3(),Zo=h.vec3(),Jo=h.vec3(),Yo=h.vec3(),qo=h.mat4();class $o extends os{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=Ko;let f,m;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Zo;if(l){const e=Jo;h.transformPoint3(c,l,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]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,qo),m=Yo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let g=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,g+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,g+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,g+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems),n.bindVertexArray(null)}_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.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class en{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),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ko(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Oo(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new No(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Vo(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Qo(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Xo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new $o(this._scene)),this._snapRenderer}_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(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const tn={};class sn{constructor(e){this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=tn[t];return i||(i=new en(e),tn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete tn[t],i._destroy()}))),i}(e.model.scene);const t=e.maxGeometryBatchSize||5e6,i=function(){const e=[];return{append:function(t,i=1,s=1){e.push({data:t,times:i,denormalizeScale:s})},compileBuffer:function(t){let i=0;e.forEach((e=>{i+=e.times*e.data.length}));const s=new t(i);let r=0;return e.forEach((e=>{const t=e.data,i=e.denormalizeScale,o=s.subarray(r);if(1===i)o.set(t,0);else for(let e=0;e<t.length;++e)o[e]=t[e]*i;let n=t.length;const a=e.times*t.length;for(;n<a;){const e=Math.min(n,a-n);o.set(o.subarray(0,e),n),n+=e}r+=n})),s}}};this._buffer={maxVerts:t,positions:i(),colors:i(),pickColors:i(),vertsIndex:0},this._scratchMemory=e.scratchMemory,this._state=new ie({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._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!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))}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}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.vertsIndex+e/3<=this._buffer.maxVerts}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=this._buffer,s=this._preCompressedPositionsExpected?t.positionsCompressed:t.positions;if(!s)throw(this._preCompressedPositionsExpected?"positionsCompressed":"positions")+" expected";i.positions.append(s);const r=s.length/3,o=t.color,n=t.colorsCompressed,a=t.colors,l=t.pickColor;n?i.colors.append(n):a?i.colors.append(a,1,255):o&&i.colors.append([o[0],o[1],o[2],1],r),i.pickColors.append(l.slice(0,4),r),h.expandAABB3(this._modelAABB,t.aabb);const A=this._portions.length/2;return this._portions.push(this._buffer.vertsIndex),this._portions.push(r),this._buffer.vertsIndex+=r,this._numPortions++,this.model.numPortions++,this._meshes.push(e),A}finalize(){if(this._finalized)return;const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer,s=(e,i,s)=>e.length>0?new se(t,t.ARRAY_BUFFER,e,e.length,i,s):null,r=this._preCompressedPositionsExpected?i.positions.compileBuffer(Uint16Array):js(i.positions.compileBuffer(Float32Array),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=s(r,3,t.STATIC_DRAW),e.flagsBuf=s(new Float32Array(this._buffer.vertsIndex),1,t.DYNAMIC_DRAW),e.colorsBuf=s(i.colors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.pickColorsBuf=s(i.pickColors.compileBuffer(Uint8Array),4,t.STATIC_DRAW),e.offsetsBuf=this.model.scene.entityOffsetsEnabled?s(new Float32Array(3*this._buffer.vertsIndex),3,t.DYNAMIC_DRAW):null,this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=4)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=2*e,r=this._portions[s],o=this._portions[s+1],n=this._scratchMemory.getFloat32Array(o),a=!!(t&Gi),l=!!(t&Ki),A=!!(t&Zi),c=!!(t&Ji),h=!!(t&zi),u=!!(t&ji);let d,p;d=!a||u||l||A&&!this.model.scene.highlightMaterial.glowThrough||c&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,p=!a||u?qi.NOT_RENDERED:c?qi.SILHOUETTE_SELECTED:A?qi.SILHOUETTE_HIGHLIGHTED:l?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let f=a&&!u&&h?qi.PICK:qi.NOT_RENDERED;const m=t&Wi?1:0;for(let e=0;e<o;e++){let t=0;t|=d,t|=p<<4,t|=f<<12,t|=m<<16,n[e]=t}this._state.flagsBuf.setData(n,r)}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 i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=n,o[e+1]=a,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.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._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.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 rn extends os{constructor(e,t){super(e,t,{instancing:!0})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArraysInstanced(t.POINTS,0,i.positionsBuf.numItems,i.numInstances),r&&s.drawArrays++}}class on extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points 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),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),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 {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),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, 1.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;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class nn extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points 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 float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),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("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class an extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh 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),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vPickColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class ln extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing 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("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push(" vec4 res = fract(depth * bitShift);"),s.push(" res -= res.xxyz * bitMask;"),s.push(" return res;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class An extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing 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;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e<t.getNumAllocatedSectionPlanes();e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".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); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class cn extends rn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing 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;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),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 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("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("const float packUpScale = 256. / 255.;"),o.push("const float unpackDownscale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),o.push("const float shiftRight8 = 1.0 / 256.;"),o.push("vec4 packDepthToRGBA( const in float v ) {"),o.push(" vec4 r = vec4( fract( v * packFactors ), v );"),o.push(" r.yzw -= r.xyz * shiftRight8;"),o.push(" return r * packUpScale;"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push(" float r = dot(cxy, cxy);"),o.push(" if (r > 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push(" dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class hn extends rn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push(" return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push(" float r = dot(cxy, cxy);"),s.push(" if (r > 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const un=h.vec3(),dn=h.vec3(),pn=h.vec3();h.vec3();const fn=h.mat4();class mn extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=un;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=dn;if(l){const e=h.transformPoint3(c,l,pn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,fn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,p),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gn=h.vec3(),_n=h.vec3(),vn=h.vec3();h.vec3();const bn=h.mat4();class yn extends os{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const p=gn;let f;if(p[0]=h.safeInv(u[3]-u[0])*h.MAX_INT,p[1]=h.safeInv(u[4]-u[1])*h.MAX_INT,p[2]=h.safeInv(u[5]-u[2])*h.MAX_INT,e.snapPickCoordinateScale[0]=h.safeInv(p[0]),e.snapPickCoordinateScale[1]=h.safeInv(p[1]),e.snapPickCoordinateScale[2]=h.safeInv(p[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=_n;if(l){const e=h.transformPoint3(c,l,vn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],f=He(d,t,bn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,p),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(f,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.bindVertexArray(null)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),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.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push("if (dist > 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class wn{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),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new on(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new nn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new cn(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new an(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ln(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new An(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new hn(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new mn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new yn(this._scene)),this._snapRenderer}_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(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Bn={};const xn=new Uint8Array(4),Pn=new Float32Array(1),Cn=new Float32Array(3),Mn=new Float32Array(4);class Fn{constructor(e){this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Bn[t];return i||(i=new wn(e),Bn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Bn[t],i._destroy()}))),i}(e.model.scene),this._aabb=h.collapseAABB3(),this._state=new ie({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._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,this.primitive=e.geometry.primitive}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}createPortion(e,t){const i=t.meshMatrix,s=t.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(i[0]),this._modelMatrixCol0.push(i[4]),this._modelMatrixCol0.push(i[8]),this._modelMatrixCol0.push(i[12]),this._modelMatrixCol1.push(i[1]),this._modelMatrixCol1.push(i[5]),this._modelMatrixCol1.push(i[9]),this._modelMatrixCol1.push(i[13]),this._modelMatrixCol2.push(i[2]),this._modelMatrixCol2.push(i[6]),this._modelMatrixCol2.push(i[10]),this._modelMatrixCol2.push(i[14]),this._pickColors.push(s[0]),this._pickColors.push(s[1]),this._pickColors.push(s[2]),this._pickColors.push(s[3]),this._state.numInstances++;const r=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,this._meshes.push(e),r}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length/4,i=this._state,s=i.geometry;if(t>0){let s=!1;i.flagsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new se(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=h.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new se(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new se(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new se(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;i.pickColorsBuf=new se(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(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,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";xn[0]=t[0],xn[1]=t[1],xn[2]=t[2],this._state.colorsBuf.setData(xn,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&Gi),r=!!(t&Ki),o=!!(t&Zi),n=!!(t&Ji),a=!!(t&Yi),l=!!(t&zi),A=!!(t&ji);let c,h;c=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,h=!s||A?qi.NOT_RENDERED:n?qi.SILHOUETTE_SELECTED:o?qi.SILHOUETTE_HIGHLIGHTED:r?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let u=0;u=!s||A?qi.NOT_RENDERED:n?qi.EDGES_SELECTED:o?qi.EDGES_HIGHLIGHTED:r?qi.EDGES_XRAYED:a?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let d=0;d|=c,d|=h<<4,d|=u<<8,d|=(s&&!A&&l?qi.PICK:qi.NOT_RENDERED)<<12,d|=(t&Wi?255:0)<<16,Pn[0]=d,this._state.flagsBuf.setData(Pn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Cn[0]=t[0],Cn[1]=t[1],Cn[2]=t[2],this._state.offsetsBuf.setData(Cn,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Mn[0]=t[0],Mn[1]=t[4],Mn[2]=t[8],Mn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Mn,i),Mn[0]=t[1],Mn[1]=t[5],Mn[2]=t[9],Mn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Mn,i),Mn[0]=t[2],Mn[1]=t[6],Mn[2]=t[10],Mn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Mn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.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._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK)}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()}}const En=h.vec3(),In=h.vec3(),Tn=h.mat4();class Dn{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=En;if(f){const t=h.transformPoint3(u,A,In);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,Tn)}else p=d;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,En,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uPerObjectDecodeMatrix="uPerObjectDecodeMatrix",this.uPerObjectColorAndFlags="uPerObjectColorAndFlags",this._uPerVertexPosition="uPerVertexPosition",this._uPerLineIndices="uPerLineIndices",this._uPerLineObject="uPerLineObject",this._uPerObjectMatrix="uPerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Sn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Dn(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Rn={};class Un{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Ln{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class kn{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const On={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(On,null,4));let e=0;Object.keys(On).forEach((t=>{t.startsWith("size")&&(e+=On[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/On.totalLines).toFixed(2)}`);let t={};Object.keys(On).forEach((i=>{i.startsWith("size")&&(t[i]=`${(On[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Nn{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);On.sizeDataColorsAndFlags+=l.byteLength,On.numberOfTextures++;for(let e=0;e<o;e++)l.set(t[e],32*e+0),l.set(i[e],32*e+4),l.set([0,0,0,0],32*e+8),l.set([0,0,0,0],32*e+12),l.set([s[e]>>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);On.sizeDataTextureOffsets+=r.byteLength,On.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);On.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r,o)}generateTextureForPositionsDecodeMatrices(e,t){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);On.sizeDataPositionDecodeMatrices+=o.byteLength,On.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureFor8BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*3);On.sizeDataTextureIndices+=o.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureFor16BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*3);On.sizeDataTextureIndices+=o.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureFor32BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*3);On.sizeDataTextureIndices+=o.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}generateTextureForPositions(e,t,i){const s=i/3,r=4096,o=Math.ceil(s/r);if(0===o)throw"texture height===0";const n=new Uint16Array(r*o*3);On.sizeDataTexturePositions+=n.byteLength,On.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];n.set(s,i),i+=s.length}const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,o),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,o,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,a,r,o)}generateTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const i=t.length,s=4096,r=Math.ceil(i/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r);o.set(t,0),On.sizeDataTexturePortionIds+=o.byteLength,On.numberOfTextures++;const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}}const Vn=new Ns,Qn=Vn.maxDataTextureHeight,Hn=new Float32Array(16),Gn=new Uint8Array(4),jn=new Float32Array(3);let zn=0;const Wn=h.identityMat4();class Xn{constructor(e,t){On.numberOfLayers++,this._layerNumber=zn++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._renderers=function(e){const t=e.id;let i=Rn[t];return i||(i=new Sn(e),Rn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Rn[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Un,this._dataTextureState=new Ln,this._dataTextureGenerator=new Nn,this._state=new ie({origin:h.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),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._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}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}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&On.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*Qn||t+r>4096*Qn)&&On.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Qn&&t+r<=4096*Qn}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;On.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,On.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||Wn),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,On.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,On.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,On.totalLines32Bits+=t.numLines),On.totalLines+=t.numLines;for(let i=0;i<t.numLines;i+=8)e.push(A)}return this._subPortions.push({numVertices:t.numLines}),this._numPortions++,On.numberOfPortions++,A}finalize(){if(this._finalized)return;const e=this._state,t=this._dataTextureState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectColorsAndFlags=this._dataTextureGenerator.generateTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dataTextureGenerator.generateTextureForInstancingMatrices(i,s.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dataTextureGenerator.generateTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dataTextureGenerator.generateTextureForPositions(i,s.positionsCompressed,s.lenPositionsCompressed),t.texturePerLineIdPortionIds8Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId8Bits),t.texturePerLineIdPortionIds16Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId16Bits),t.texturePerLineIdPortionIds32Bits=this._dataTextureGenerator.generateTextureForPackedPortionIds(i,s.perLineNumberPortionId32Bits),s.lenIndices8Bits>0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetColor(i[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;Gn[0]=t[0],Gn[1]=t[1],Gn[2]=t[2],Gn[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(Gn,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Gn))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e<o;e++)this._subPortionSetFlags(r[e],t,i,s)}_subPortionSetFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=!!(t&Gi),o=!!(t&Ki),n=!!(t&ji);let a,l;a=!r||n||o?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,l=!r||n?qi.NOT_RENDERED:!!(t&Ji)?qi.SILHOUETTE_SELECTED:!!(t&Zi)?qi.SILHOUETTE_HIGHLIGHTED:o?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let A=r&&!n&&!!(t&zi)?qi.PICK:qi.NOT_RENDERED;const c=this._dataTextureState,h=this.model.scene.canvas.gl;Gn[0]=a,Gn[1]=l,Gn[3]=A,c.texturePerObjectColorsAndFlags._textureData.set(Gn,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),h.bindTexture(h.TEXTURE_2D,c.texturePerObjectColorsAndFlags._texture),h.texSubImage2D(h.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,h.RGBA_INTEGER,h.UNSIGNED_BYTE,Gn))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e<r;e++)this._subPortionSetFlags2(s[e],t,i)}_subPortionSetFlags2(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=t&Wi?255:0,r=this._dataTextureState,o=this.model.scene.canvas.gl;Gn[0]=s,Gn[1]=0,Gn[2]=1,Gn[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(Gn,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Gn))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetOffset(i[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;jn[0]=t[0],jn[1]=t[1],jn[2]=t[2],i.texturePerObjectOffsets._textureData.set(jn,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,jn))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetMatrix(i[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=this._dataTextureState,s=this.model.scene.canvas.gl;Hn.set(t),i.texturePerObjectInstanceMatrices._textureData.set(Hn,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Hn))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const Kn=h.vec3(),Zn=h.vec3(),Jn=h.vec3();h.vec3();const Yn=h.vec4(),qn=h.mat4();class $n{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=Kn;if(f){const t=h.transformPoint3(u,A,Zn);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=He(r.viewMatrix,e,qn),p=Jn,p[0]=r.eye[0]-e[0],p[1]=r.eye[1]-e[1],p[2]=r.eye[2]-e[2]}else d=r.viewMatrix,p=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,p),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;s.crossSections&&(n.uniform4fv(this._uSliceColor,s.crossSections.sliceColor),n.uniform1f(this._uSliceThickness,s.crossSections.sliceThickness));for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Kn,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new it(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}this._uSceneModelMatrix=s.getLocation("sceneModelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=s.getLocation("uCameraEyeRtc"),e.crossSections&&(this._uSliceColor=s.getLocation("sliceColor"),this._uSliceThickness=s.getLocation("sliceThickness"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState.lights,o=t.camera.project;s.bind(),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=r.length;e<t;e++){const t=r[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;Yn[0]=t,Yn[1]=r,Yn[2]=s.blendCutoff,Yn[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,Yn),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,10)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));s&&(o.push("out vec4 vWorldPosition;"),o.push("flat out uint vFlags2;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int polygonIndex = gl_VertexID / 3;"),o.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),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;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = vec3(color.rgb) / 255.0;"),o.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags2 = flags2.r;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer 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"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";");s.push("uniform float sliceThickness;"),s.push("uniform vec4 sliceColor;")}if(s.push("in vec4 vColor;"),s.push("out vec4 outColor;"),s.push("void main(void) {"),s.push(" vec4 newColor;"),s.push(" newColor = vColor;"),i){s.push(" bool clippable = vFlags2 > 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled?s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"):(s.push(" float dx = dFdx(gl_FragCoord.z);"),s.push(" float dy = dFdy(gl_FragCoord.z);"),s.push(" float diff = sqrt(dx*dx+dy*dy);"),s.push(" gl_FragDepth = gl_FragCoord.z + diff;")),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ea=new Float32Array([1,1,1]),ta=h.vec3(),ia=h.vec3(),sa=h.vec3();h.vec3();const ra=h.mat4();class oa{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o,d=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const e=ta;if(A){const t=ia;h.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,ra),f=sa,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=d,f=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===qi.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,ea);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),g=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*g,r=o.renderFlags;for(let t=0;t<m;t++){const s=this._uSectionPlanes[t];if(s)if(t<g){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ta,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture 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;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("uniform vec4 color;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = color;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const na=new Float32Array([0,0,0,1]),aa=h.vec3(),la=h.vec3();h.vec3();const Aa=h.mat4();class ca{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=aa;if(f){const t=h.transformPoint3(u,A,la);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,Aa)}else p=d;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===qi.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===qi.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,na);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,aa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),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;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ha=h.vec3(),ua=h.vec3(),da=h.mat4();class pa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=ha;if(f){const t=h.transformPoint3(u,A,ua);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,da)}else p=d;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ha,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix"}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.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;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),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;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";");i.push("uniform float sliceThickness;"),i.push("uniform vec4 sliceColor;")}if(i.push("in vec4 vColor;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" vec4 newColor;"),i.push(" newColor = vColor;"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > sliceThickness) { "),i.push(" discard;"),i.push(" }"),i.push(" if (dist > 0.0) { "),i.push(" newColor = sliceColor;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = newColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const fa=h.vec3(),ma=h.vec3(),ga=h.vec3(),_a=h.mat4();class va{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=e.pickViewMatrix||o.viewMatrix,p=e.pickProjMatrix||o.projMatrix,f=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let g,_;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==c[0]||0!==c[1]||0!==c[2];if(v||b){const e=fa;if(v){const t=h.transformPoint3(u,A,ma);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],g=He(d,e,_a),_=ga,_[0]=f[0]-e[0],_[1]=f[1]-e[1],_[2]=f[2]-e[2]}else g=d,_=f;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),w=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*w,o=s.renderFlags;for(let t=0;t<y;t++){const r=this._uSectionPlanes[t];if(r)if(t<w){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,fa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry 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"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("in vec4 vPickColor;"),i.push("out vec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ba=h.vec3(),ya=h.vec3(),wa=h.vec3();h.vec3();const Ba=h.mat4();class xa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=e.pickViewMatrix||o.viewMatrix,p=e.pickProjMatrix||o.projMatrix,f=e.pickOrigin||o.eye,m=e.pickProjMatrix?e.pickZFar:o.project.far;let g,_;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const t=ba;if(A){const e=ya;h.transformPoint3(u,A,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],g=He(d,t,Ba),_=wa,_[0]=f[0]-t[0],_[1]=f[1]-t[1],_[2]=f[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=d,_=f,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const v=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(v>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*b,o=s.renderFlags;for(let t=0;t<v;t++){const r=this._uSectionPlanes[t];if(r)if(t<b){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ba,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth 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;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push("uniform bool sectionPlaneActive"+s+";"),i.push("uniform vec3 sectionPlanePos"+s+";"),i.push("uniform vec3 sectionPlaneDir"+s+";")}if(i.push("in vec4 vViewPosition;"),i.push("vec4 packDepth(const in float depth) {"),i.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),i.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),i.push(" vec4 res = fract(depth * bitShift);"),i.push(" res -= res.xxyz * bitMask;"),i.push(" return res;"),i.push("}"),i.push("out vec4 outPackedDepth;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Pa=h.vec3(),Ca=h.vec3(),Ma=h.vec3(),Fa=h.vec3();h.vec3();const Ea=h.mat4();class Ia{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix,f=Pa;let m,g;f[0]=h.safeInv(d[3]-d[0])*h.MAX_INT,f[1]=h.safeInv(d[4]-d[1])*h.MAX_INT,f[2]=h.safeInv(d[5]-d[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]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const _=0!==A[0]||0!==A[1]||0!==A[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(_||v){const t=Ca;if(_){const e=h.transformPoint3(u,A,Ma);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],m=He(p,t,Ea),g=Fa,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t<b;t++){const r=this._uSectionPlanes[t];if(r)if(t<y){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Pa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}const w="edge"===e.snapMode?n.LINES:n.POINTS;a.numEdgeIndices8Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(w,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(w,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(w,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdEdgeIndices="uTexturePerPolygonIdEdgeIndices",this._uTexturePerEdgeIdPortionIds="uTexturePerEdgeIdPortionIds",this._uTextureModelMatrices="uTextureModelMatrices",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this.uVectorA=i.getLocation("uSnapVectorA"),this.uInverseVectorAB=i.getLocation("uSnapInvVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),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("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("out highp ivec4 outCoords;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ta=h.vec3(),Da=h.vec3(),Sa=h.vec3(),Ra=h.vec3();h.vec3();const Ua=h.mat4();class La{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix,f=Ta;let m,g;f[0]=h.safeInv(d[3]-d[0])*h.MAX_INT,f[1]=h.safeInv(d[4]-d[1])*h.MAX_INT,f[2]=h.safeInv(d[5]-d[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]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const _=0!==A[0]||0!==A[1]||0!==A[2],v=0!==c[0]||0!==c[1]||0!==c[2];if(_||v){const t=Da;if(_){const e=Sa;h.transformPoint3(u,A,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],m=He(p,t,Ua),g=Ra,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const b=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(b>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*y,o=s.renderFlags;for(let t=0;t<b;t++){const r=this._uSectionPlanes[t];if(r)if(t<y){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Ta,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uLogDepthBufFC=i.getLocation("logDepthBufFC"),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc"),this._uVectorA=i.getLocation("uVectorAB"),this._uInverseVectorAB=i.getLocation("uInverseVectorAB"),this._uLayerNumber=i.getLocation("uLayerNumber"),this._uCoordinateScaler=i.getLocation("uCoordinateScaler")}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("}"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer 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 float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in highp vec3 relativeToOriginPosition;"),i.push("layout(location = 0) out highp ivec4 outCoords;"),i.push("layout(location = 1) out highp ivec4 outNormal;"),i.push("layout(location = 2) out lowp uvec4 outPickColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ka=h.vec3(),Oa=h.vec3(),Na=h.vec3();h.vec3();const Va=h.mat4();class Qa{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=s,d=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==c[0]||0!==c[1]||0!==c[2]){const e=ka;if(A){const t=Oa;h.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],p=He(d,e,Va),f=Na,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),g=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*g,o=s.renderFlags;for(let t=0;t<m;t++){const r=this._uSectionPlanes[t];if(r)if(t<g){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,ka,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(){const e=this._scene;e.canvas.gl,e.camera.project,this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer 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){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out vec4 outColor;"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t<e.getNumAllocatedSectionPlanes();t++)i.push(" if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ha=h.vec3(),Ga=h.vec3(),ja=h.vec3();h.vec3();const za=h.mat4();class Wa{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const f=0!==A[0]||0!==A[1]||0!==A[2],m=0!==c[0]||0!==c[1]||0!==c[2];if(f||m){const e=Ha;if(f){const t=h.transformPoint3(u,A,Ga);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],d=He(r.viewMatrix,e,za),p=ja,p[0]=r.eye[0]-e[0],p[1]=r.eye[1]-e[1],p[2]=r.eye[2]-e[2]}else d=r.viewMatrix,p=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,p),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const g=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(g>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t<g;t++){const s=this._uSectionPlanes[t];if(s)if(t<_){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,Ha,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture 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"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xa=h.vec3(),Ka=h.vec3(),Za=h.vec3();h.vec3();const Ja=h.mat4();class Ya{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const f=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(f||m){const e=Xa;if(f){const t=Ka;h.transformPoint3(c,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],d=He(u,e,Ja),p=Za,p[0]=o.eye[0]-e[0],p[1]=o.eye[1]-e[1],p[2]=o.eye[2]-e[2]}else d=u,p=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,d),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const g=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(g>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<g;t++){const r=this._uSectionPlanes[t];if(r)if(t<_){const a=o.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(r.active,a?1:0),a){const i=e[t];if(l){const e=ze(i.dist,i.dir,l,Xa,s.matrix);n.uniform3fv(r.pos,e)}else n.uniform3fv(r.pos,i.pos);n.uniform3fv(r.dir,i.dir)}}else n.uniform1i(r.active,0)}}n.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.objectDecodeAndInstanceMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aNormal.bindArrayBuffer(a.normalsBuf),this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),n.drawElements(n.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.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);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(st.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),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&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t<e._sectionPlanesState.getNumAllocatedSectionPlanes();t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("in vec3 vViewNormal;"),i.push("vec3 packNormalToRGB( const in vec3 normal ) {"),i.push(" return normalize( normal ) * 0.5 + 0.5;"),i.push("}"),i.push("void main(void) {"),t){i.push(" bool clippable = (float(vFlags2.x) > 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s<e._sectionPlanesState.getNumAllocatedSectionPlanes();s++)i.push(" if (sectionPlaneActive"+s+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push(" }");i.push(" if (dist > 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&st.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const qa=h.vec3(),$a=h.vec3(),el=h.vec3();h.vec3(),h.vec4();const tl=h.mat4();class il{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:c,rotationMatrix:u}=o;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a));const d=e.pickViewMatrix||r.viewMatrix,p=e.pickProjMatrix||r.projMatrix,f=e.pickOrigin||r.eye,m=e.pickProjMatrix?e.pickZFar:r.project.far;let g,_;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==c[0]||0!==c[1]||0!==c[2];if(v||b){const e=qa;if(v){const t=h.transformPoint3(u,A,$a);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=c[0],e[1]+=c[1],e[2]+=c[2],g=He(d,e,tl),_=el,_[0]=f[0]-e[0],_[1]=f[1]-e[1],_[2]=f[2]-e[2]}else g=d,_=f;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,g),n.uniformMatrix4fv(this._uProjMatrix,!1,p),n.uniform3fv(this._uCameraEyeRtc,_),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const e=2/(Math.log(m+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),w=s._sectionPlanesState.sectionPlanes.length;if(y>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*w,r=o.renderFlags;for(let t=0;t<y;t++){const s=this._uSectionPlanes[t];if(s)if(t<w){const a=r.sectionPlanesActivePerLayer[i+t];if(n.uniform1i(s.active,a?1:0),a){const i=e[t];if(A){const e=ze(i.dist,i.dir,A,qa,o.matrix);n.uniform3fv(s.pos,e)}else n.uniform3fv(s.pos,i.pos);n.uniform3fv(s.dir,i.dir)}}else n.uniform1i(s.active,0)}}a.numIndices8Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new it(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC")),this.uTexturePerObjectPositionsDecodeMatrix="uObjectPerObjectPositionsDecodeMatrix",this.uTexturePerObjectColorsAndFlags="uObjectPerObjectColorsAndFlags",this._uTexturePerVertexIdCoordinates="uTexturePerVertexIdCoordinates",this._uTexturePerPolygonIdNormals="uTexturePerPolygonIdNormals",this._uTexturePerPolygonIdIndices="uTexturePerPolygonIdIndices",this._uTexturePerPolygonIdPortionIds="uTexturePerPolygonIdPortionIds",this._uTexturePerObjectMatrix="uTexturePerObjectMatrix",this._uCameraEyeRtc=i.getLocation("uCameraEyeRtc")}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer 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;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("out highp ivec4 outNormal;"),i.push("void main(void) {"),t){i.push(" bool clippable = vFlags2 > 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t<s;t++)i.push("if (sectionPlaneActive"+t+") {"),i.push(" dist += clamp(dot(-sectionPlaneDir"+t+".xyz, vWorldPosition.xyz - sectionPlanePos"+t+".xyz), 0.0, 1000.0);"),i.push("}");i.push(" if (dist > 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${h.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class sl{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._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=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._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=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)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new oa(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new va(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new xa(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new il(this._scene)),this._snapRenderer||(this._snapRenderer=new Ia(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new La(this._scene)),this._snapRenderer||(this._snapRenderer=new Ia(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new $n(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new $n(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new oa(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Wa(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ya(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new ca(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new pa(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new va(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new il(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new il(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new xa(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ia(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new La(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Qa(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.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._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const rl={};class ol{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class nl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const al={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(al,null,4));let e=0;Object.keys(al).forEach((t=>{t.startsWith("size")&&(e+=al[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/al.totalPolygons).toFixed(2)}`);let t={};Object.keys(al).forEach((i=>{i.startsWith("size")&&(t[i]=`${(al[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class ll{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const c=new Uint8Array(16384*A);al.sizeDataColorsAndFlags+=c.byteLength,al.numberOfTextures++;for(let e=0;e<a;e++)c.set(t[e],32*e+0),c.set(i[e],32*e+4),c.set([0,0,0,0],32*e+8),c.set([0,0,0,0],32*e+12),c.set([s[e]>>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),c.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),c.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),c.set([n[e]?1:0,0,0,0],32*e+28);const h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,c,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,h,l,A,c)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);al.sizeDataTextureOffsets+=r.byteLength,al.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);al.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r,o)}createTextureForPositionsDecodeMatrices(e,t){const i=t.length;if(0===i)throw"num decode+entity matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);al.sizeDataPositionDecodeMatrices+=o.byteLength,al.numberOfTextures++;for(let e=0;e<t.length;e++)o.set(t[e],16*e);const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA32F,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGBA,e.FLOAT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor8BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*3);al.sizeDataTextureIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor16BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*3);al.sizeDataTextureIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor32BitIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/3/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*3);al.sizeDataTextureIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RGB_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor8BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint8Array(s*r*2);al.sizeDataTextureEdgeIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG8UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_BYTE,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor16BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r*2);al.sizeDataTextureEdgeIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_SHORT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureFor32BitsEdgeIndices(e,t,i){if(0===i)return{texture:null,textureHeight:0};const s=4096,r=Math.ceil(i/2/s);if(0===r)throw"texture height===0";const o=new Uint32Array(s*r*2);al.sizeDataTextureEdgeIndices+=o.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];o.set(s,i),i+=s.length}const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RG32UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RG_INTEGER,e.UNSIGNED_INT,o,0),this.disableBindedTextureFiltering(e),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}createTextureForPositions(e,t,i){const s=i/3,r=4096,o=Math.ceil(s/r);if(0===o)throw"texture height===0";const n=new Uint16Array(r*o*3);al.sizeDataTexturePositions+=n.byteLength,al.numberOfTextures++;for(let e=0,i=0,s=t.length;e<s;e++){const s=t[e];n.set(s,i),i+=s.length}const a=e.createTexture();return e.bindTexture(e.TEXTURE_2D,a),e.texStorage2D(e.TEXTURE_2D,1,e.RGB16UI,r,o),e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,o,e.RGB_INTEGER,e.UNSIGNED_SHORT,n,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,a,r,o)}createTextureForPackedPortionIds(e,t){if(0===t.length)return{texture:null,textureHeight:0};const i=t.length,s=4096,r=Math.ceil(i/s);if(0===r)throw"texture height===0";const o=new Uint16Array(s*r);o.set(t,0),al.sizeDataTexturePortionIds+=o.byteLength,al.numberOfTextures++;const n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.R16UI,s,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,s,r,e.RED_INTEGER,e.UNSIGNED_SHORT,o,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new kn(e,n,s,r)}}const Al=new Ns,cl=Al.maxDataTextureHeight,hl=h.vec4(),ul=new Float32Array(16),dl=new Uint8Array(4),pl=new Float32Array(3);let fl=0;const ml=h.identityMat4();class gl{constructor(e,t){al.numberOfLayers++,this._layerNumber=fl++,this.sortId=`TriDTX-${this._layerNumber}`,this.layerIndex=t.layerIndex,this._renderers=function(e){const t=e.id;let i=rl[t];return i||(i=new sl(e),rl[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete rl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new ol,this._dtxState=new nl,this._dtxTextureFactory=new ll,this._state=new ie({origin:h.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),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._subPortions=[],this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries={}),this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=h.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this.primitive=t.primitive,this._finalized=!1}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}canCreatePortion(e){if(this._finalized)throw"Already finalized";const t=e.buckets.length;this._numPortions+t>65536&&al.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*cl||t+r>4096*cl)&&al.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*cl&&t+r<=4096*cl}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;al.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;al.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,c=0;if(s){let e;c=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let h=0;if(r){let e;h=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,al.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:c,numEdges:h,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,c=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||ml),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?c.numIndices8Bits:t.numVertices<=65536?c.numIndices16Bits:c.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?c.numEdgeIndices8Bits:t.numVertices<=65536?c.numEdgeIndices16Bits:c.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const h=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,c.numIndices8Bits+=i,al.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,c.numIndices16Bits+=i,al.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,c.numIndices32Bits+=i,al.totalPolygons32Bits+=t.numTriangles),al.totalPolygons+=t.numTriangles;for(let i=0;i<t.numTriangles;i+=8)e.push(h)}if(t.numEdges>0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,c.numEdgeIndices8Bits+=i,al.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,c.numEdgeIndices16Bits+=i,al.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,c.numEdgeIndices32Bits+=i,al.totalEdges32Bits+=t.numEdges),al.totalEdges+=t.numEdges;for(let i=0;i<t.numEdges;i+=8)e.push(h)}return this._subPortions.push({numVertices:t.numTriangles}),this.model.scene.readableGeometryEnabled&&(this._subPortionReadableGeometries[h]={indices:i.indices,positionsCompressed:i.positionsCompressed,positionsDecodeMatrix:e.positionsDecodeMatrix,meshMatrix:e.meshMatrix}),this._numPortions++,al.numberOfPortions++,h}finalize(){if(this._finalized)return;const e=this._state,t=this._dtxState,i=this.model.scene.canvas.gl,s=this._buffer;e.gl=i,t.texturePerObjectColorsAndFlags=this._dtxTextureFactory.createTextureForColorsAndFlags(i,s.perObjectColors,s.perObjectPickColors,s.perObjectVertexBases,s.perObjectIndexBaseOffsets,s.perObjectEdgeIndexBaseOffsets,s.perObjectSolid),t.texturePerObjectInstanceMatrices=this._dtxTextureFactory.createTextureForInstancingMatrices(i,s.perObjectInstancePositioningMatrices),t.texturePerObjectPositionsDecodeMatrix=this._dtxTextureFactory.createTextureForPositionsDecodeMatrices(i,s.perObjectPositionsDecodeMatrices),t.texturePerVertexIdCoordinates=this._dtxTextureFactory.createTextureForPositions(i,s.positionsCompressed,s.lenPositionsCompressed),t.texturePerPolygonIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId8Bits),t.texturePerPolygonIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId16Bits),t.texturePerPolygonIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perTriangleNumberPortionId32Bits),s.perEdgeNumberPortionId8Bits.length>0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&Gi&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&Zi&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&Ki&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ji&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Wi&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Yi&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&zi&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&ji&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&Gi?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&Zi?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&Ki?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&Ji?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&Yi?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Wi?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&ji?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&zi?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetColor(i[e],t)}_subPortionSetColor(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;dl[0]=t[0],dl[1]=t[1],dl[2]=t[2],dl[3]=t[3],i.texturePerObjectColorsAndFlags._textureData.set(dl,32*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,dl))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e<o;e++)this._subPortionSetFlags(r[e],t,i,s)}_subPortionSetFlags(e,t,i,s=!1){if(!this._finalized)throw"Not finalized";const r=!!(t&Gi),o=!!(t&Ki),n=!!(t&Zi),a=!!(t&Ji),l=!!(t&Yi),A=!!(t&zi),c=!!(t&ji);let h,u;h=!r||c||o||n&&!this.model.scene.highlightMaterial.glowThrough||a&&!this.model.scene.selectedMaterial.glowThrough?qi.NOT_RENDERED:i?qi.COLOR_TRANSPARENT:qi.COLOR_OPAQUE,u=!r||c?qi.NOT_RENDERED:a?qi.SILHOUETTE_SELECTED:n?qi.SILHOUETTE_HIGHLIGHTED:o?qi.SILHOUETTE_XRAYED:qi.NOT_RENDERED;let d=0;d=!r||c?qi.NOT_RENDERED:a?qi.EDGES_SELECTED:n?qi.EDGES_HIGHLIGHTED:o?qi.EDGES_XRAYED:l?i?qi.EDGES_COLOR_TRANSPARENT:qi.EDGES_COLOR_OPAQUE:qi.NOT_RENDERED;let p=r&&!c&&A?qi.PICK:qi.NOT_RENDERED;const f=this._dtxState,m=this.model.scene.canvas.gl;dl[0]=h,dl[1]=u,dl[2]=d,dl[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(dl,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),m.bindTexture(m.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),m.texSubImage2D(m.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,m.RGBA_INTEGER,m.UNSIGNED_BYTE,dl))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e<r;e++)this._subPortionSetFlags2(s[e],t,i)}_subPortionSetFlags2(e,t,i=!1){if(!this._finalized)throw"Not finalized";const s=t&Wi?255:0,r=this._dtxState,o=this.model.scene.canvas.gl;dl[0]=s,dl[1]=0,dl[2]=1,dl[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(dl,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,dl))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetOffset(i[e],t)}_subPortionSetOffset(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;pl[0]=t[0],pl[1]=t[1],pl[2]=t[2],i.texturePerObjectOffsets._textureData.set(pl,3*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,pl))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e<s;e++)this._subPortionSetMatrix(i[e],t)}_subPortionSetMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=this._dtxState,s=this.model.scene.canvas.gl;ul.set(t),i.texturePerObjectInstanceMatrices._textureData.set(ul,16*e),this._deferredSetFlagsActive?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,ul))}getEachVertex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._state,s=this._portionToSubPortionsMap[e];if(s)for(let e=0,r=s.length;e<r;e++){const r=s[e],o=this._subPortionReadableGeometries[r],n=o.positionsCompressed,a=o.positionsDecodeMatrix;o.meshMatrix;const l=i.origin,A=l[0],c=l[1],u=l[2],d=hl;for(let e=0,i=n.length;e<i;e+=3)d[0]=n[e],d[1]=n[e+1],d[2]=n[e+2],d[3]=1,h.decompressPosition(d,a),h.mulMat4v4(this.model.worldMatrix,d,d),d[0]+=A,d[1]+=c,d[2]+=u,t(d)}else this.model.error("portion not found: "+e)}getEachIndex(e,t){if(!this.model.scene.readableGeometryEnabled)return;const i=this._portionToSubPortionsMap[e];if(i)for(let e=0,s=i.length;e<s;e++){const s=i[e],r=this._subPortionReadableGeometries[s].indices;for(let e=0,i=r.length;e<i;e++)t(r[e])}else this.model.error("portion not found: "+e)}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?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,qi.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}_updateBackfaceCull(e,t){if(true!==t.backfaces){const e=t.gl;e.disable(e.CULL_FACE),t.backfaces=true}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,qi.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._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,qi.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._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,qi.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,qi.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,qi.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,qi.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,qi.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,qi.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,qi.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,qi.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,qi.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class _l{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.alphaCutoff=e.alphaCutoff,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class vl{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const bl={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 yl{constructor(e,t,i){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=i}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,i=this.handlers.length;t<i;t+=2){const i=this.handlers[t],s=this.handlers[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return s}return null}}const wl=new yl;class Bl{constructor(e){this.manager=void 0!==e?e:wl,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise((function(s,r){i.load(e,s,t,r)}))}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 xl={};class Pl extends Bl{constructor(e){super(e)}load(e,t,i,s){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=bl.get(e);if(void 0!==r)return this.manager.itemStart(e),M.scheduleTask((()=>{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==xl[e])return void xl[e].push({onLoad:t,onProgress:i,onError:s});xl[e]=[],xl[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).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 i=xl[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e<t;e++){const t=i[e];t.onProgress&&t.onProgress(s)}e.enqueue(r),t()}}))}()}});return new Response(l)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{bl.add(e,t);const i=xl[e];delete xl[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onLoad&&s.onLoad(t)}})).catch((t=>{const i=xl[e];if(void 0===i)throw this.manager.itemError(e),t;delete xl[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onError&&s.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 Cl{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:t,msg:i,transfer:s}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,s)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((i=>{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=i,this.workers[s].postMessage(e,t)):this.queue.push({resolve:i,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 Ml=0;class Fl{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Cl,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.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"),i=new Pl;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=Fl.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(Fl.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Fl.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Fl.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),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}))})),Ml>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Ml++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:c,dfdTransferFn:h,dfdFlags:u}=i;if("error"===A)return r(c);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Ml--}}Fl.BasisFormat={ETC1S:0,UASTC_4x4:1},Fl.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},Fl.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},Fl.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const c=n.data;switch(c.type){case"init":e=c.config,h=c.transcoderBinary,t=new Promise((e=>{i={wasmBinary:h,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function c(){n.close(),n.delete()}if(!n.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),m=n.getDFDTransferFunc(),g=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,c){let h,u;const d=t===o.ETC1S?a:l;for(let s=0;s<d.length;s++){const r=d[s];if(e[r.if]&&(r.basisFormat.includes(t)&&!(c&&r.transcoderFormat.length<2)&&(!r.needsPowerOfTwo||A(i)&&A(n))))return h=r.transcoderFormat[c?1:0],u=r.engineFormat[c?1:0],{transcoderFormat:h,engineFormat:u}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=r.RGBA32,u=s.RGBAFormat,{transcoderFormat:h,engineFormat:u}}(h,u,d,f);if(!u||!d||!p)throw c(),new Error("KTX2TextureTranscoder: Invalid texture");if(!n.startTranscoding())throw c(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const b=[];for(let e=0;e<p;e++){const t=n.getImageLevelInfo(e,0,0),i=t.origWidth,s=t.origHeight,r=new Uint8Array(n.getImageTranscodedSizeInBytes(e,0,0,_));if(!n.transcodeImage(r,e,0,0,_,0,-1,-1))throw c(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");b.push({data:r,width:i,height:s})}return c(),{width:u,height:d,hasAlpha:f,mipmaps:b,format:v,dfdTransferFn:m,dfdFlags:g}}(c.buffers[0]),m=[];for(let e=0;e<u.length;++e)m.push(u[e].data.buffer);self.postMessage({type:"transcode",id:c.id,width:t,height:n,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f},m)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:c.id,error:e.message})}}))}var h}));const n=[{if:"astcSupported",basisFormat:[o.UASTC_4x4],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[s.RGBA_ASTC_4x4_Format,s.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[s.RGBA_BPTC_Format,s.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.BC1,r.BC3],engineFormat:[s.RGB_S3TC_DXT1_Format,s.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[s.RGB_ETC2_Format,s.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.ETC1],engineFormat:[s.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[o.ETC1S,o.UASTC_4x4],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[s.RGB_PVRTC_4BPPV1_Format,s.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],a=n.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),l=n.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function A(e){return e<=2||0==(e&e-1)&&0!==e}};const El={};function Il(e){const t=e.scene.id;let i=El[t];return i||(i=new Fl({viewer:e}),El[t]=i,e.scene.on("destroyed",(()=>{delete El[t],i.destroy()}))),i}
@@ -20,7 +20,7 @@
20
20
  /**
21
21
  * @author https://github.com/tmarti, with support from https://tribia.com/
22
22
  * @license MIT
23
- **/let Ul=null;function Ll(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const c=Math.min(r=Ul[i],o=Ul[i+1],n=Ul[i+2]),h=Math.min(a=Ul[s],l=Ul[s+1],A=Ul[s+2]);if(c!==h)return c-h;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let kl=null;function Ol(e,t){let i=kl[2*e]-kl[2*t];return 0!==i?i:kl[2*e+1]-kl[2*t+1]}function Nl(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e<t;e++)i[e]=e;Ul=new Int32Array(e.length);for(let i=0,s=e.length;i<s;i++)Ul[i]=e[i]>>t;i.sort(Ll);const s=new Int32Array(e.length);for(let t=0,r=i.length;t<r;t++)s[3*t+0]=e[3*i[t]+0],s[3*t+1]=e[3*i[t]+1],s[3*t+2]=e[3*i[t]+2];return s}(e.indices||[],t),o=function(e){if(0===(e||[]).length)return[];let t=new Int32Array(e.length/2);for(let e=0,i=t.length;e<i;e++)t[e]=e;for(let t=0,i=e.length;t<i;t+=2)if(e[t]>e[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}kl=new Int32Array(e),t.sort(Ol);const i=new Int32Array(e.length);for(let s=0,r=t.length;s<r;s++)i[2*s+0]=e[2*t[s]+0],i[2*s+1]=e[2*t[s]+1];return i}(e.edgeIndices||[]);function n(e,t){if(e>t){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<<t))return[e];const A=new Int32Array(l);A.fill(-1);const c=[];function h(){A.fill(-1);const e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}let u=h();for(let t=0,i=r.length;t<i;t+=3){let i=0;const l=r[t],c=r[t+1],d=r[t+2];if(-1===A[l]&&i++,-1===A[c]&&i++,-1===A[d]&&i++,i+u.numPositions>u.maxNumPositions&&(u=h()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[c]&&(A[c]=u.numPositions++,u.positionsCompressed.push(s[3*c]),u.positionsCompressed.push(s[3*c+1]),u.positionsCompressed.push(s[3*c+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[c]),u.indices.push(A[d]),(p=n(l,c))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(c,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let m=0,g=-s.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,g+=e.positionsCompressed.length/3})),m>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e<s;e+=3){const s=n[3*t[e]]+"_"+n[3*t[e]+1]+"_"+n[3*t[e]+2]+"/"+n[3*t[e+1]]+"_"+n[3*t[e+1]+1]+"_"+n[3*t[e+1]+2]+"/"+n[3*t[e+2]]+"_"+n[3*t[e+2]+1]+"_"+n[3*t[e+2]+2];i[s]=!0}r+=e.edgeIndices.length/2;for(let e=0,t=o.length;e<t;e+=2){const t=n[3*o[e]]+"_"+n[3*o[e]+1]+"_"+n[3*o[e]+2]+"/"+n[3*o[e+1]]+"_"+n[3*o[e+1]+1]+"_"+n[3*o[e+1]+2]+"/";s[t]=!0}}));{const e=t.indices;t.edgeIndices;const s=t.positionsCompressed;for(let t=0,r=e.length;t<r;t+=3){const r=s[3*e[t]]+"_"+s[3*e[t]+1]+"_"+s[3*e[t]+2]+"/"+s[3*e[t+1]]+"_"+s[3*e[t+1]+1]+"_"+s[3*e[t+1]+2]+"/"+s[3*e[t+2]]+"_"+s[3*e[t+2]+1]+"_"+s[3*e[t+2]+2];if(!(r in i))throw console.log("Not found "+r),"Ohhhh!"}}}(c,e),c)}const Vl=new Float32Array([0,0,0]),Ql=new Uint16Array([0,0,0]);h.OBB3();class Hl{constructor(e,t,i,s,r,o){this._isObject=t,this.scene=e.scene,this.model=e,this.isSceneModelEntity=!0,this.meshes=s,this._numPrimitives=0,this._capMaterial=null;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=i,this.originalSystemId=h.unglobalizeObjectId(e.id,i),this._flags=r,this._aabb=h.AABB3(),this._aabbDirty=!0,this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!o,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(Gi)}set visible(e){if(!!(this._flags&Gi)!==e){this._flags=e?this._flags|Gi:this._flags&~Gi;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(Zi)}set highlighted(e){if(!!(this._flags&Zi)!==e){this._flags=e?this._flags|Zi:this._flags&~Zi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(Ki)}set xrayed(e){if(!!(this._flags&Ki)!==e){this._flags=e?this._flags|Ki:this._flags&~Ki;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(Ji)}set selected(e){if(!!(this._flags&Ji)!==e){this._flags=e?this._flags|Ji:this._flags&~Ji;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(Yi)}set edges(e){if(!!(this._flags&Yi)!==e){this._flags=e?this._flags|Yi:this._flags&~Yi;for(var t=0,i=this.meshes.length;t<i;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&ji)!==e){this._flags=e?this._flags|ji:this._flags&~ji;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(Wi)}set clippable(e){if(!!(this._flags&Wi)!==e){this._flags=e?this._flags|Wi:this._flags&~Wi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(Xi)}set collidable(e){if(!!(this._flags&Xi)!==e){this._flags=e?this._flags|Xi:this._flags&~Xi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(zi)}set pickable(e){if(!!(this._flags&zi)!==e){this._flags=e?this._flags|zi:this._flags&~zi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return Vl[0]=e[0]/255,Vl[1]=e[1]/255,Vl[2]=e[2]/255,Vl}set colorize(e){if(e){Ql[0]=Math.floor(255*e[0]),Ql[1]=Math.floor(255*e[1]),Ql[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(Ql)}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,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(s,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}set capMaterial(e){this.scene.readableGeometryEnabled&&(this._capMaterial=e instanceof Xt?e:null,this.scene._capMaterialUpdated(this.id,this.model.id))}get capMaterial(){return this._capMaterial}getEachVertex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachVertex(e)}getEachIndex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachIndex(e)}getGeometryData(){let e=0;const t=[],i=[];for(let s=0,r=this.meshes.length;s<r;s++){const r=this.meshes[s];if(r.layer.readGeometryData){const s=r.layer.readGeometryData(r.portionId);for(let t=0,r=s.indices.length;t<r;t++)i.push(s.indices[t]+e);for(let e=0,i=s.positions.length;e<i;e++)t.push(s.positions[e]);e+=s.positions.length/3}}return{indices:i,positions:t}}get volume(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].volume;if(i<0)return-1;e+=i}return e}get surfaceArea(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].surfaceArea;i>=0&&(e+=i)}return e>0?e:-1}_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._deRegisterVisibleObject(this),this.xrayed&&e._deRegisterXRayedObject(this),this.selected&&e._deRegisterSelectedObject(this),this.highlighted&&e._deRegisterHighlightedObject(this),this._colorizeUpdated&&this.scene._deRegisterColorizedObject(this),this._opacityUpdated&&this.scene._deRegisterOpacityObject(this),!this._offset||0===this._offset[0]&&0===this._offset[1]&&0===this._offset[2]||this.scene._deRegisterOffsetObject(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const Gl=h.vec4(4),jl=h.vec4(),zl=h.vec4(),Wl=h.vec3([1,0,0]),Xl=h.vec3([0,1,0]),Kl=h.vec3([0,0,1]);h.vec3(3),h.vec3(3);const Zl=h.identityMat4();class Jl{constructor(e){this._model=e.model,this.id=e.id,this._parentTransform=e.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=h.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=h.identityMat4(new Float32Array(16)),this._worldMatrix=h.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,e.matrix?this.matrix=e.matrix:(this.scale=e.scale,this.position=e.position,e.quaternion||(this.rotation=e.rotation)),e.parent&&e.parent._addChildTransform(this)}_addChildTransform(e){this._childTransforms.push(e),e._parentTransform=this,e._transformDirty(),e._setSubtreeAABBsDirty(this)}_addMesh(e){this._meshes.push(e),e.transform=this}get parentTransform(){return this._parentTransform}get meshes(){return this._meshes}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.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._model.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._model.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||Zl),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.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 Gl[0]=e[0],Gl[1]=e[1],Gl[2]=e[2],Gl[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Gl,jl),h.mulQuaternions(this.quaternion,jl,zl),this.quaternion=zl,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return Gl[0]=e[0],Gl[1]=e[1],Gl[2]=e[2],Gl[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Gl,jl),h.mulQuaternions(jl,this.quaternion,jl),this}rotateX(e){return this.rotate(Wl,e)}rotateY(e){return this.rotate(Xl,e)}rotateZ(e){return this.rotate(Kl,e)}translate(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateX(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateY(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateZ(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._transformDirty()}_transformDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._childTransforms.length;e<t;e++){const t=this._childTransforms[e];if(t._transformDirty(),t._meshes&&t._meshes.length>0){const e=t._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}if(this._meshes&&this._meshes.length>0){const e=this._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}_buildWorldMatrix(){const e=this.matrix;if(this._parentTransform)h.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._childTransforms)for(let t=0,i=e._childTransforms.length;t<i;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}const Yl=h.vec3(),ql=h.OBB3(),$l=h.vec4(),eA=h.vec3([1,1,1]),tA=h.vec3([0,0,0]);h.vec3([0,0,0]);const iA=h.identityQuaternion(),sA=h.identityMat4(),rA=new Uint8Array([255,255,255]);class oA extends T{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!1,this._vboBatchingLayerScratchMemory=(Hi++,Qi),this._textureTranscoder=t.textureTranscoder||Il(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=h.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._layersToFinalize=[],this._entityList=[],this._entitiesToFinalize=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._transforms={},this._meshes={},this._unusedMeshes={},this._entities={},this.renderFlags=new Rt,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._layersFinalized=!1,this._edgeThreshold=t.edgeThreshold||10,this._origin=h.vec3(t.origin||[0,0,0]),this._position=h.vec3(t.position||[0,0,0]),this._rotation=h.vec3(t.rotation||[0,0,0]),this._quaternion=h.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=h.vec4(t.quaternion||[0,0,0,1]),t.rotation&&h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=h.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=h.mat4(),this._worldRotationMatrixConjugate=h.mat4(),this._matrix=h.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=h.mat4(),h.inverseMat4(this._matrix,this._worldNormalMatrix),h.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=h.mat4(),this._viewNormalMatrix=h.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),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.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new vl({id:"defaultColorTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new vl({id:"defaultMetalRoughTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new vl({id:"defaultNormalsTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new vl({id:"defaultEmissiveTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new vl({id:"defaultOcclusionTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new _l({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),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._setWorldMatrixDirty(),this._sceneModelDirty(),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._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||sA),h.decomposeMat4(this._matrix,this._position,this._quaternion,this._scale),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(h.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),h.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),h.quaternionToRotationMat4(this._conjugateQuaternion,this._worldRotationMatrixConjugate),h.scaleMat4v(this._scale,this._worldRotationMatrix),h.scaleMat4v(this._scale,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),h.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._viewMatrixDirty=!0)}get rotationMatrixConjugate(){return this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}get worldMatrix(){return this.matrix}get worldNormalMatrix(){return this._worldNormalMatrix}_rebuildViewMatrices(){this._rebuildMatrices(),this._viewMatrixDirty&&(h.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),h.inverseMat4(this._viewMatrix,this._viewNormalMatrix),h.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1)}get viewMatrix(){return this._viewMatrix?(this._rebuildViewMatrices(),this._viewMatrix):this.scene.camera.viewMatrix}get viewNormalMatrix(){return this._viewNormalMatrix?(this._rebuildViewMatrices(),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}get backfaces(){return this._backfaces}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get entityList(){return this._entityList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){if(this._aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._entityList.length;e<t;e++)h.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}get visible(){return this.numVisibleLayerPortions>0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].visible=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].xrayed=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].highlighted=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].selected=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].edges=e;this.glRedraw()}get culled(){return this._culled}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].culled=e;this.glRedraw()}get clippable(){return this._clippable}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].clippable=e;this.glRedraw()}get collidable(){return this._collidable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].collidable=e}get pickable(){return this.numPickableLayerPortions>0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].pickable=e}get colorize(){return this._colorize}set colorize(e){this._colorize=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].colorize=e}get opacity(){return this._opacity}set opacity(e){this._opacity=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].opacity=e}get castsShadow(){return this._castsShadow}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get colorTextureEnabled(){return this._colorTextureEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}createQuantizationRange(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:zs(e.aabb,h.mat4())}:this.error("[createQuantizationRange] Config missing: id")}createGeometry(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`[createGeometry] Param expected: indices (required for '${e.primitive}' primitive type)`),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=zs(e.positionsDecodeBoundary,h.mat4())),e.positions){const t=h.collapseAABB3();e.positionsDecodeMatrix=h.mat4(),h.expandAABB3Points3(t,e.positions),e.positionsCompressed=js(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=h.collapseAABB3();e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed),h.expandAABB3Points3(t,e.positionsCompressed),he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}else if(e.buckets){const t=h.collapseAABB3();this._dtxBuckets[e.id]=e.buckets;for(let i=0,s=e.buckets.length;i<s;i++){const s=e.buckets[i];s.positions?h.expandAABB3Points3(t,s.positions):s.positionsCompressed&&h.expandAABB3Points3(t,s.positionsCompressed)}e.positionsDecodeMatrix&&he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e<s;e++)i[e]=255*t[e];e.colorsCompressed=i}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=re(e.positions,e.indices,null,5):e.edgeIndices=re(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){const t=he.getUVBounds(e.uv),i=he.compressUVs(e.uv,t.min,t.max);e.uvCompressed=i.quantized,e.uvDecodeMatrix=i.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error(`[createGeometry] Unsupported value for 'primitive': '${e.primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);else this.error("[createGeometry] Config missing: id")}createTexture(e){const t=e.id;if(null==t)return void this.error("[createTexture] Config missing: id");if(this._textures[t])return void this.error("[createTexture] Texture already created: "+t);if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;let i=e.minFilter||1008;1006!==i&&1007!==i&&1008!==i&&1005!==i&&1004!==i&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),i=1008);let s=e.magFilter||1006;1006!==s&&1003!==s&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),s=1006);let r=e.wrapS||1e3;1001!==r&&1002!==r&&1e3!==r&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),r=1e3);let o=e.wrapT||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);let n=e.wrapR||1e3;1001!==n&&1002!==n&&1e3!==n&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),n=1e3);let a=e.encoding||3e3;3e3!==a&&3001!==a&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),a=3e3);const l=new ei({gl:this.scene.canvas.gl,minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,encoding:a});if(e.preloadColor&&l.setPreloadColor(e.preloadColor),e.image){const t=e.image;if(t.crossOrigin="Anonymous",t.compressed){const e=t.data;l.setCompressedData({mipmaps:e,props:{format:e[0].format,minFilter:i,magFilter:s}})}else l.setImage(t,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const A=new Image;A.onload=()=>{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new vl({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new _l({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new Jl({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?h.addVec3(this._origin,e.origin,h.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||eA,i=e.position||tA;e.rotation?(h.eulerToQuaternion(e.rotation,"XYZ",$l),e.meshMatrix=h.composeMat4(i,$l,t,h.mat4())):e.meshMatrix=h.composeMat4(i,e.quaternion||iA,t,h.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=zs(e.positionsDecodeBoundary,h.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):rA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=h.vec3(),i=[];je(e.positions,i,t)&&(e.positions=i,e.origin=h.addVec3(e.origin,t,t))}if(e.positions){const t=h.collapseAABB3();e.positionsDecodeMatrix=h.mat4(),h.expandAABB3Points3(t,e.positions),e.positionsCompressed=js(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=h.collapseAABB3();h.expandAABB3Points3(t,e.positionsCompressed),he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=h.collapseAABB3();for(let i=0,s=e.buckets.length;i<s;i++){const s=e.buckets[i];s.positions?h.expandAABB3Points3(t,s.positions):s.positionsCompressed&&h.expandAABB3Points3(t,s.positionsCompressed)}e.positionsDecodeMatrix&&he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}e.meshMatrix&&(h.AABB3ToOBB3(e.aabb,ql),h.transformOBB3(e.meshMatrix,ql),h.OBB3ToAABB3(ql,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=re(e.positions,e.indices,null,2):e.edgeIndices=re(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=nA(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];je(e.positions,t,Yl)&&(e.positions=t,e.origin=h.addVec3(e.origin,Yl,h.vec3()))}if(e.positions){const t=h.collapseAABB3();e.meshMatrix&&(h.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),h.expandAABB3Points3(t,e.positions),e.aabb=t}else{const t=h.collapseAABB3();h.expandAABB3Points3(t,e.positionsCompressed),he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.meshMatrix&&(h.AABB3ToOBB3(e.aabb,ql),h.transformOBB3(e.meshMatrix,ql),h.OBB3ToAABB3(ql,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=re(e.positions,e.indices,null,2):e.edgeIndices=re(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`),!1}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)"),!1;if(e.geometry=this._geometries[e.geometryId],!e.geometry)return this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`),!1;if(e.origin=e.origin?h.addVec3(this._origin,e.origin,h.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return this.error(`[createMesh] Transform not found: ${e.transformId} - ensure that you create it first with createTransform()`),!1;e.aabb=e.geometry.aabb}else{if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||eA,i=e.position||tA;e.rotation?(h.eulerToQuaternion(e.rotation,"XYZ",$l),e.meshMatrix=h.composeMat4(i,$l,t,h.mat4())):e.meshMatrix=h.composeMat4(i,e.quaternion||iA,t,h.mat4())}h.AABB3ToOBB3(e.geometry.aabb,ql),h.transformOBB3(e.meshMatrix,ql),e.aabb=h.OBB3ToAABB3(ql,h.AABB3())}if(!(!this._dtxEnabled||"triangles"!==e.geometry.primitive&&"solid"!==e.geometry.primitive&&"surface"!==e.geometry.primitive||e.textureSetId)){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):rA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=nA(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):rA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId])}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createDefaultIndices(e){const t=[];for(let i=0;i<e;i++)t.push(i);return t}_createMesh(e){const t=new Vi(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);const i=t.pickId,s=i>>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=h.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:const i=e.geometry;t+=i.positions?i.positions.length:i.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}_getDTXLayer(e){const t=e.origin,i=e.geometry?e.geometry.primitive:e.primitive,s=`.${i}.${Math.round(t[0])}.${Math.round(t[1])}.${Math.round(t[2])}`;let r=this._dtxLayers[s];if(r){if(r.canCreatePortion(e))return r;delete this._dtxLayers[s],r=null}switch(i){case"triangles":case"solid":case"surface":r=new gl(this,{layerIndex:0,origin:t,primitive:i});break;case"lines":r=new Xn(this,{layerIndex:0,origin:t,primitive:i});break;default:return}return this._dtxLayers[s]=r,this.layerList.push(r),this._layersToFinalize.push(r),r}_getVBOBatchingLayer(e){const t=this,i=e.origin;e.renderLayer;const s=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",r=e.textureSetId||"-",o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${e.primitive}.${s}.${r}`;let n=this._vboBatchingLayers[o];if(n)return n;let a=e.textureSet;for(;!n;){switch(e.primitive){case"triangles":case"solid":case"surface":n=new rr({model:t,textureSet:a,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0,primitive:e.primitive});break;case"lines":n=new fo({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive});break;case"points":n=new sn({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive})}const s=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?n.canCreatePortion(s):n.canCreatePortion(s,e.indices.length))||(n.finalize(),delete this._vboBatchingLayers[o],n=null)}return this._vboBatchingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}_createHashStringFromMatrix(e){const t=e.join("");let i=0;for(let e=0;e<t.length;e++){i=(i<<5)-i+t.charCodeAt(e),i|=0}return(i>>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Zr({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Zr({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Uo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new Fn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}createEntity(e){if(void 0===e.id?e.id=h.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=h.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=Gi),this._pickable&&!1!==e.pickable&&(t|=zi),this._culled&&!1!==e.culled&&(t|=ji),this._clippable&&!1!==e.clippable&&(t|=Wi),this._collidable&&!1!==e.collidable&&(t|=Xi),this._edges&&!1!==e.edges&&(t|=Yi),this._xrayed&&!1!==e.xrayed&&(t|=Ki),this._highlighted&&!1!==e.highlighted&&(t|=Zi),this._selected&&!1!==e.selected&&(t|=Ji),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;i<s;i++){const s=e.meshIds[i];let r=this._meshes[s];r?r.parent?this.error(`Mesh with ID "${s}" already belongs to object with ID "${r.parent.id}" - ignoring this mesh`):(t.push(r),delete this._unusedMeshes[s]):this.error(`Mesh with this ID not found: "${s}" - ignoring this mesh`)}const i=new Hl(this,e.isObject,e.id,t,e.flags,!0);return this._entityList.push(i),this._entities[e.id]=i,this._entitiesToFinalize.push(i),this.numEntities++,i}preFinalize(){if(this.destroyed)return!1;if(0===this._layersToFinalize.length)return!1;this._createDummyEntityForUnusedMeshes();for(let e=0,t=this._layersToFinalize.length;e<t;e++){this._layersToFinalize[e].finalize()}this._vboBatchingLayers={},this._vboInstancingLayers={},this._dtxLayers={},this._layersToFinalize=[];for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize()}for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize2()}this._entitiesToFinalize=[],this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position,this.layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].layerIndex=e}this.glRedraw(),this._layersFinalized=!0}finalize(){this.destroyed||(this.preFinalize(),this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={})}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t<i;t++){const i=this.layerList[t];this._getActiveSectionPlanesForLayer(i)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_createDummyEntityForUnusedMeshes(){const e=Object.keys(this._unusedMeshes);if(e.length>0){const t=`${this.id}-${h.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e<s;e++){i[e].active?(t.sectionPlanesActivePerLayer[r+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[r+e]=!1}return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t<s;t++){const s=i.visibleLayers[t];this.layerList[s].drawColorOpaque(i,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawShadow(t,e)}}setPickMatrices(e,t){if(0===this._numVisibleLayerPortions)return;const i=this.renderFlags;for(let s=0,r=i.visibleLayers.length;s<r;s++){const r=i.visibleLayers[s],o=this.layerList[r];o.setPickMatrices&&o.setPickMatrices(e,t)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickNormals(t,e)}}drawSnapInit(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnapInit&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnapInit(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}drawSnap(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnap&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnap(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}destroy(){for(let e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();this._vboBatchingLayers={};for(let e in this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(e)&&this._vboInstancingLayers[e].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(let e=0,t=this.layerList.length;e<t;e++)this.layerList[e].destroy();this.layerList=[];for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._destroy();this._layersToFinalize={},this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==Hi&&(Hi--,0===Hi&&Qi._clear()),super.destroy()}}function nA(e,t,i){let s,r,o,n;if(t||i?[s,r,o]=Rl({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(s=e.positionsCompressed,r=e.indices,o=e.edgeIndices),i){n=Nl({positionsCompressed:s,indices:r,edgeIndices:o},s.length/3>65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class aA extends T{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],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._color=t.color||[1,1,1],this._opacity=t.opacity||1,this._sceneModel=new oA(this,{isModel:!1}),this._sceneModel.createMesh({id:"linesMesh",primitive:"lines",positions:this._positions,indices:this._indices,color:this._color,opacity:this._opacity}),this._sceneModel.createEntity({meshIds:["linesMesh"],visible:t.visible,clippable:t.clippable,collidable:t.collidable}),this._sceneModel.finalize(),this.scene._lineSetCreated(this)}set visible(e){this._sceneModel.visible=e}get visible(){return this._sceneModel.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}class lA extends T{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class AA extends lA{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 cA{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.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,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e<r.length;e++)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+e,s.TEXTURE_2D,r[e],0);if(e.length>0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},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,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,i||c.RGBA,s||c.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,c=new Uint8Array(4*n);for(let e=0;e<l;++e){const t=e*A,s=(a-e-1)*A;c.set(i.subarray(t,t+A)),i.copyWithin(t,s,s+A),i.set(c,s)}return r.data.set(i),o.putImageData(r,0,0),s}readImage(e){const t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,o=i.imageData,n=i.context,{width:a,height:l}=this.buffer;t.readPixels(0,0,a,l,t.RGBA,t.UNSIGNED_BYTE,s),o.data.set(s),n.putImageData(o,0,0),n.save(),n.globalCompositeOperation="copy",n.scale(1,-1),n.drawImage(r,0,-l,a,l),n.restore();let A=e.format||"png";return"jpeg"!==A&&"png"!==A&&"bmp"!==A&&(console.error("Unsupported image format: '"+A+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),A="png"),r.toDataURL(`image/${A}`)}_getImageDataCache(e=Uint8Array,t=4){const i=this.buffer.width,s=this.buffer.height;let r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){const o=document.createElement("canvas"),n=o.getContext("2d");o.width=i,o.height=s,r={pixelData:new e(i*s*t),canvas:o,context:n,imageData:n.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}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(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),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 hA extends lA{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 i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new ie({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,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];h.lookAtMat4v(s,i,r,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 cA(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()}}function uA(e){if(!dA(e.width)||!dA(e.height)){const t=document.createElement("canvas");t.width=pA(e.width),t.height=pA(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function dA(e){return 0==(e&e-1)}function pA(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class fA extends T{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new ie({texture:new ei({gl:i,target:i.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),p.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,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o<e.length;o++){const n=new Image;n.onload=function(){let e=n;const a=o;return function(){if(!s&&(e=uA(e),t._images[a]=e,r++,6===r)){let e=t._state.texture;e||(e=new ei({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),n.onerror=function(){s=!0},n.src=e[o]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),p.memory.textures--,this._state.destroy()}}const mA=h.vec4(),gA=h.vec4();class _A extends T{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){mA.set(this._viewPos),mA[3]=1,h.transformPoint4(this.scene.camera.projMatrix,mA,gA);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+gA[0]/gA[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-gA[1]/gA[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){this._entity!==e&&(this._cleanupDestroyedHandlers(),this._entity=e,this._entity&&(this._entity.isSceneModelEntity?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,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),Ge(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._cleanupDestroyedHandlers(),this._renderer.removeMarker(this),super.destroy()}_cleanupDestroyedHandlers(){this._entity&&(null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null))}}class vA{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,i=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:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const bA=h.vec3();const yA=h.vec3();class wA{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?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,c=!t||t.colorize,h=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),c){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}h&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,c=!t||t.opacity;var h=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[h]),s&&(t.edges=this.objectsEdges[h]),r&&(t.xrayed=this.objectsXrayed[h]),o&&(t.highlighted=this.objectsHighlighted[h]),n&&(t.selected=this.objectsSelected[h]),a&&(t.clippable=this.objectsClippable[h]),l&&(t.pickable=this.objectsPickable[h]),A&&(this.objectsHasColorize[h]?(yA[0]=this.objectsColorize[3*h+0],yA[1]=this.objectsColorize[3*h+1],yA[2]=this.objectsColorize[3*h+2],t.colorize=yA):t.colorize=null),c&&(t.opacity=this.objectsOpacity[h]),h++}}}const BA=h.vec3(),xA=h.vec3(),PA=h.vec4(),CA=h.vec3([0,0,-1]),MA=h.vec3([0,0,1]),FA=h.vec3([0,1,0]);class EA extends T{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new ie({active:!0,pos:h.vec3(),quaternion:h.vec4(),roll:0,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),this.scene.fire("sectionPlaneUpdated",this)}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 quaternion(e){this._state.quaternion.set(e||[0,0,0,-1]),h.vec3ApplyQuaternion(this._state.quaternion,MA,this._state.dir);const t=h.vec3ApplyQuaternion(this._state.quaternion,FA,BA),i=h.vec3PairToQuaternion(MA,this._state.dir,PA),s=h.vec3ApplyQuaternion(i,FA,xA),r=Math.acos(Math.min(1,h.dotVec3(t,s))),o=Math.sign(h.dotVec3(this._state.dir,h.cross3Vec3(t,s,xA)));this._state.roll=o*r,this._onDirUpdated()}get quaternion(){return this._state.quaternion}set roll(e){this._state.roll=e||0,this._onDirRollUpdated()}get roll(){return this._state.roll}set dir(e){this._state.dir.set(e||CA),this._onDirRollUpdated()}_onDirRollUpdated(){h.vec3PairToQuaternion(MA,this._state.dir,this._state.quaternion),PA[0]=0,PA[1]=0,PA[2]=-1,PA[3]=this._state.roll,h.angleAxisToQuaternion(PA,PA),h.mulQuaternions(this._state.quaternion,PA,this._state.quaternion),this._onDirUpdated()}_onDirUpdated(){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(){h.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}class IA{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}get snapped(){return this.snappedToEdge||this.snappedToVertex}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}}const TA={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isIphoneOrIpadSafari(){const e=window.navigator.userAgent,t=/iPhone|iPad/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isTouchDevice:()=>"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.mxMaxTouchPoints>0};class DA{constructor(e,t,i){this.id=i&&i.id?i.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)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}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)}}class SA extends T{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,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.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 i=this._element;i&&(i.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 RA=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class UA extends T{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 i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new SA(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],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<RA.length;e++)try{this.gl=this.canvas.getContext(RA[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="__",i=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,i.call(this,e))};let s={},r=e.bindTexture;e.bindTexture=function(e,i){s[t]!==i&&(s[t]=i,r.call(this,e,i))}}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,i,s){return this.scene._renderer.readPixels(e,t,i,s)}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 LA{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 i=this._rtcViewMats[e];return i||(i=this._getNewMat(),He(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}getRTCPickViewMatrix(e,t){let i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();const s=this.pickViewMatrix||this._scene.camera.viewMatrix;He(s,t,i),this._rtcPickViewMats[e]=i}return i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=h.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}class kA{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 i=this.markerList[t].rtcPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[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(new Float32Array(this.positions));this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new se(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3];let o=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const i=this.markerList[e];if(i.viewPos[2]>-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i];if(t.active){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const s=0===e;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const OA=h.vec3([1,0,0]),NA=h.vec3();class VA{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 i=this._occlusionLayers[t];i||(i=new kA(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new kA(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.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,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new it(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,o=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,i=this._occlusionLayersList.length;e<i;e++){const i=this._occlusionLayersList[e];if(i.update(),i.culledBySectionPlanes)continue;const o=i.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,He(r.viewMatrix,o));const n=s.sectionPlanes.length;if(n>0){const e=s.sectionPlanes;for(let s=0;s<n;s++){const r=this._uSectionPlanes[s];if(r){const n=i.sectionPlanesActive[s];if(t.uniform1i(r.active,n?1:0),n){const i=e[s];t.uniform3fv(r.pos,ze(i.dist,i.dir,o,NA)),t.uniform3fv(r.dir,i.dir)}}}}this._aPosition.bindArrayBuffer(i.positionsBuf);const a=i.indicesBuf;a.bind(),t.drawElements(t.POINTS,a.numItems,a.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*OA[0],i=255*OA[1],s=255*OA[2];for(let r=0,o=this._occlusionLayersList.length;r<o;r++){const o=this._occlusionLayersList[r];for(let r=0;r<o.lenOcclusionTestList;r++){const n=o.occlusionTestList[r],a=2*r,l=this._readPixelBuf.read(Math.round(o.pixels[a]*e),Math.round(o.pixels[a+1]*e)),A=l[0]===t&&l[1]===i&&l[2]===s;n._setVisible(A)}}}}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 QA=h.vec2();class HA{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,this.init()}init(){this._rebuild=!0}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(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,c=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;QA[0]=o,QA[1]=n,t.viewport(0,0,o,n),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),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,QA),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.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&&!this._rebuild)return;this._rebuild=!1;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new it(i,{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 s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new se(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new se(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new se(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.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 GA=new Float32Array(ZA(17,[0,1])),jA=new Float32Array(ZA(17,[1,0])),zA=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(KA(s,t));return i}(17,4)),WA=new Float32Array(2);class XA{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 it(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]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new se(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new se(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new se(e,e.ELEMENT_ARRAY_BUFFER,s,s.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,i){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(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,c=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),WA[0]=n,WA[1]=a,s.uniform2fv(this._uViewport,WA),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,c),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,jA):s.uniform2fv(this._uSampleOffsets,GA),s.uniform1fv(this._uSampleWeights,zA);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function KA(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ZA(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class JA{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new cA(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}const YA=h.vec3([0,0,0]),qA=function(t,i){i=i||{};const s=new LA(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},c={},u=[],d=[],f=[],m=!0,g=!0,_=!0,v=!0,b=!0,y=!0,w=!0,B=!0;const x=new JA(t);let P=!1;const C=new HA(t),M=new XA(t);function F(){m&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),m=!1,g=!0),g&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;t<s;t++){const s=i[t];u[e++]=s}}u.length=e,u.sort(((e,t)=>e.renderOrder-t.renderOrder))}(),g=!1,_=!0),_&&function(){let e=0,t=0;for(let i=0,s=u.length;i<s;i++){const s=u[i];s.rebuildRenderFlags(),s.renderFlags.culled||(s.isUI?f[t++]=s:d[e++]=s)}d.length=e,f.length=t}()}function E(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.shadowViewMatrix=e.getShadowViewMatrix(),s.shadowProjMatrix=e.getShadowProjMatrix(),o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,1),o.enable(o.DEPTH_TEST),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];!1!==i.visible&&i.castsShadow&&i.drawShadow&&(i.renderFlags.colorOpaque&&i.drawShadow(s))}}t.unbind()}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!Yt(o,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Yt(o,"WEBGL_compressed_texture_etc"),dxtSupported:!!Yt(o,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Yt(o,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Yt(o,"WEBGL_compressed_texture_pvrtc")&&!Yt(o,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){v=e,_=!0},this.setEdgesEnabled=function(e){b=e,_=!0},this.setSAOEnabled=function(e){y=e,_=!0},this.setPBREnabled=function(e){w=e,_=!0},this.setColorTextureEnabled=function(e){B=e,_=!0},this.needStateSort=function(){g=!0},this.shadowsDirty=function(){},this.imageDirty=function(){_=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){C.init(),M.init(),_=!0},this.addDrawable=function(e,t){const i=t.type;if(!i)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let s=A[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},A[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,m=!0},this.removeDrawable=function(e){const t=c[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const i=t.type,s=A[i];--s.count<=0?delete A[i]:delete s.drawableMap[e],delete c[e],m=!0},this.getPickID=function(e){return l.addItem(e)},this.putPickID=function(e){l.removeItem(e)},this.clear=function(e){if(o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT)},this.needsRender=function(){return _||m||g},this.render=function(e){(e=e||{}).force&&(_=!0),F(),_&&(!function(e){const i=t.sao;y&&i.possible&&function(e){const i=t.sao,r=x.getRenderBuffer("saoDepth",{depthTexture:!0});r.bind(),r.clear(),function(e){s.reset(),s.pass=e.pass,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=d.length;e<t;e++){const t=d[e];!0!==t.culled&&!1!==t.visible&&t.drawDepth&&t.saoEnabled&&(t.renderFlags.colorOpaque&&t.drawDepth(s))}}(e),r.unbind();const n=x.getRenderBuffer("saoOcclusion");if(n.bind(),n.clear(),C.render(r),n.unbind(),i.blur){const e=x.getRenderBuffer("saoOcclusion2");e.bind(),e.clear(),M.render(r,n,0),e.unbind(),n.bind(),n.clear(),M.render(r,e,1),n.unbind()}}(e);(function(){let e=t._lightsState.lights;for(let t=0,i=e.length;t<i;t++){const i=e[t];i.castsShadow&&E(i)}})(),function(e){const i=[],r=[],l=[],A=[],c=[],u=[],m=[],g=[],_=[],P=[],C=[],M=[],F=[],E=[],I=[],T=[],D=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=e.pass,s.withSAO=!1,s.pbrEnabled=w&&!!t.pbrEnabled,s.colorTextureEnabled=B&&!!t.colorTextureEnabled,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?D:t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),o.lineWidth(1),s.lineWidth=1;const S=t.sao.possible;if(y&&S){const e=x.getRenderBuffer("saoOcclusion");s.occlusionTexture=e?e.getTexture():null}else s.occlusionTexture=null;let R,U;const L=Date.now();!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const k=function(e){let d=0,p=0,f=0,w=0,B=0,x=0,D=0,L=0,k=0,O=0,N=0,V=0,Q=0,H=0,G=0,j=0;for(let t=0,o=e.length;t<o;t++){if(U=e[t],!0===U.culled||!1===U.visible)continue;const o=U.renderFlags;o.colorOpaque&&(y&&S&&U.saoEnabled?i[d++]=U:U.drawColorOpaque(s)),v&&o.colorTransparent&&(l[f++]=U),o.xrayedSilhouetteTransparent&&(m[D++]=U),o.xrayedSilhouetteOpaque&&(c[B++]=U),o.highlightedSilhouetteTransparent&&(C[N++]=U),o.highlightedSilhouetteOpaque&&(_[k++]=U),o.selectedSilhouetteTransparent&&(I[G++]=U),o.selectedSilhouetteOpaque&&(F[Q++]=U),U.edges&&b&&(o.edgesOpaque&&(r[p++]=U),o.edgesTransparent&&(A[w++]=U),o.selectedEdgesTransparent&&(T[j++]=U),o.selectedEdgesOpaque&&(E[H++]=U),o.xrayedEdgesTransparent&&(g[L++]=U),o.xrayedEdgesOpaque&&(u[x++]=U),o.highlightedEdgesTransparent&&(M[V++]=U),o.highlightedEdgesOpaque&&(P[O++]=U))}if(d>0)for(s.withSAO=!0,R=0;R<d;R++)i[R].drawColorOpaque(s);if(p>0)for(R=0;R<p;R++)r[R].drawEdgesColorOpaque(s);if(B>0)for(R=0;R<B;R++)c[R].drawSilhouetteXRayed(s);if(x>0)for(R=0;R<x;R++)u[R].drawEdgesXRayed(s);if(D>0||L>0||f>0||w>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(f>0||w>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),w>0)for(R=0;R<w;R++)U=A[R],U.drawEdgesColorTransparent(s);if(f>0){const e=s.pickOrigin||t.camera.eye,i=l.map((t=>({drawable:t,distSq:h.distVec3(t.origin||YA,e)})));for(i.sort(((e,t)=>t.distSq-e.distSq)),R=0;R<f;R++)i[R].drawable.drawColorTransparent(s)}if(L>0)for(R=0;R<L;R++)g[R].drawEdgesXRayed(s);if(D>0)for(R=0;R<D;R++)m[R].drawSilhouetteXRayed(s);o.disable(o.BLEND),a||o.depthMask(!0)}if(k>0||O>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),O>0)for(R=0;R<O;R++)P[R].drawEdgesHighlighted(s);if(k>0)for(R=0;R<k;R++)_[R].drawSilhouetteHighlighted(s)}if(N>0||V>0||k>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),V>0)for(R=0;R<V;R++)M[R].drawEdgesHighlighted(s);if(N>0)for(R=0;R<N;R++)C[R].drawSilhouetteHighlighted(s);o.disable(o.BLEND)}if(Q>0||H>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),H>0)for(R=0;R<H;R++)E[R].drawEdgesSelected(s);if(Q>0)for(R=0;R<Q;R++)F[R].drawSilhouetteSelected(s)}if(G>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),j>0)for(R=0;R<j;R++)T[R].drawEdgesSelected(s);if(G>0)for(R=0;R<G;R++)I[R].drawSilhouetteSelected(s);o.disable(o.BLEND)}};k(d),f.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),k(f));const O=Date.now(),N=p.frame;N.renderTime=(O-L)/1e3,N.drawElements=s.drawElements,N.drawArrays=s.drawArrays,N.useProgram=s.useProgram,N.bindTexture=s.bindTexture,N.bindArray=s.bindArray;const V=st.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<V;e++)o.activeTexture(o.TEXTURE0+e);o.bindTexture(o.TEXTURE_CUBE_MAP,null),o.bindTexture(o.TEXTURE_2D,null);const Q=st.MAX_VERTEX_ATTRIBS;for(let e=0;e<Q;e++)o.disableVertexAttribArray(e)}(e)}(e),p.frame.frameCount++,_=!1)},this.pick=function(){const e=h.vec3();h.mat4();const i=h.mat4(),n=h.vec3(),a=h.vec3([0,1,0]),c=new IA,u=h.vec2(),p=h.vec3(),m=h.vec3(),g=h.vec3();return h.vec3(),h.vec3(),function(_,v=c){let b;v.reset(),F();let y=null,w=null,B=null;v.pickSurface=_.pickSurface,_.canvasPos?(p[0]=_.canvasPos[0],p[1]=_.canvasPos[1],y=t.camera.viewMatrix,w=t.camera.projMatrix,B=t.camera.projection,u[0]=t.camera.project.near,u[1]=t.camera.project.far,v.canvasPos=_.canvasPos):(_.matrix?(y=_.matrix,w=t.camera.projMatrix,B=t.camera.projection,u[0]=t.camera.project.near,u[1]=t.camera.project.far):(m.set(_.origin||[0,0,0]),g.set(_.direction||[0,0,1]),b=h.addVec3(m,g,e),n[0]=Math.random(),n[1]=Math.random(),n[2]=Math.random(),h.normalizeVec3(n),h.cross3Vec3(g,n,a),y=h.lookAtMat4v(m,b,a,i),w=t.camera.ortho.matrix,B="ortho",u[0]=t.camera.ortho.near,u[1]=t.camera.ortho.far,v.origin=m,v.direction=g),p[0]=.5*r.clientWidth,p[1]=.5*r.clientHeight);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(y,w)}}const P=x.getRenderBuffer("pick",{size:[1,1]});P.bind();const C=function(e,i,r,n,a,A){const c=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=A.origin,s.pickViewMatrix=r,s.pickProjMatrix=n,s.pickInvisible=!!a.pickInvisible,s.pickClipPos=[D(i[0]*c,o.drawingBufferWidth),S(i[1]*c,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const h=a.includeEntityIds,u=a.excludeEntityIds,p=function(e){for(let t=0,i=e.length;t<i;t++){const i=e[t];!0!==i.culled&&!1!==i.visible&&(!i.drawPickMesh||!0!==a.pickInvisible&&!1===i.visible||!1===i.pickable||h&&!h[i.id]||u&&u[i.id]||i.drawPickMesh(s))}};p(d),f.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),p(f));const m=e.read(0,0),g=m[0]+(m[1]<<8)+(m[2]<<16)+(m[3]<<24);if(g<0)return;return l.items[g]}(P,p,y,w,_,v);if(!C)return P.unbind(),null;const M=C.delegatePickedEntity?C.delegatePickedEntity():C;return M?(_.pickSurface&&(C.canPickTriangle&&C.canPickTriangle()?(!function(e,i,r,n,a,l){if(!i.drawPickTriangles)return;const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),i.drawPickTriangles(s);const c=e.read(0,0);let h=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;h*=3,l.primIndex=h}(P,C,p,y,w,v),C.pickTriangleSurface(y,w,B,v),v.pickSurfacePrecision=!1):C.canPickWorldPos&&C.canPickWorldPos()&&(I(P,C,p,y,w,u,v),!1!==_.pickSurfaceNormal&&function(e,i,r,n,a,l){const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)];const c=x.getRenderBuffer("pick-normal",{size:[3,3]});c.bind(o.RGBA32I),o.viewport(0,0,c.size[0],c.size[1]),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),i.drawPickNormals(s);const u=c.read(1,1,o.RGBA_INTEGER,o.INT,Int32Array,4);c.unbind();const d=[u[0]/h.MAX_INT,u[1]/h.MAX_INT,u[2]/h.MAX_INT];h.normalizeVec3(d),l.worldNormal=d}(0,C,p,y,w,v),v.pickSurfacePrecision=!1)),P.unbind(),v.entity=M,v):(P.unbind(),null)}}();const I=function(){const e=h.vec4(),i=h.vec4(),n=h.vec4(),a=h.vec4(),l=h.vec4(),A=h.mat4(),c=h.mat4(),u=h.mat4();return function(d,p,f,m,g,_,v){const b=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=v.origin,s.pickViewMatrix=m,s.pickProjMatrix=g,s.pickZNear=_[0],s.pickZFar=_[1],s.pickElementsCount=p.pickElementsCount,s.pickElementsOffset=p.pickElementsOffset,s.pickClipPos=[D(f[0]*b,o.drawingBufferWidth),S(f[1]*b,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),p.drawPickDepths(s);const y=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],i=[1/16777216,1/65536,1/256,1];return h.dotVec4(t,i)}(d.read(0,0)),w=(f[0]-r.clientWidth/2)/(r.clientWidth/2),B=-(f[1]-r.clientHeight/2)/(r.clientHeight/2),x=p.origin;let P;if(x){const e=He(m,x,A);P=h.mulMat4(g,e,c)}else P=h.mulMat4(g,m,c);const C=h.inverseMat4(P,u);e[0]=w,e[1]=B,e[2]=-1,e[3]=1;let M=h.transformVec4(C,e);M=h.mulVec4Scalar(M,1/M[3]),i[0]=w,i[1]=B,i[2]=1,i[3]=1;let F=h.transformVec4(C,i);F=h.mulVec4Scalar(F,1/F[3]);const E=h.subVec3(F,M,n),I=h.addVec3(M,h.mulVec4Scalar(E,y,a),l);x&&h.addVec3(I,x),v.worldPos=I}}();function T(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(let t=0,i=d.length;t<i;t++){const i=d[t];i.drawSnapInit&&i.drawSnap&&!i.culled&&i.visible&&i.pickable&&i.drawSnap(e)}return e.snapPickLayerParams}function D(e,t){return e/t*2-1}function S(e,t){return 1-e/t*2}this.snapPick=function(){const e=new IA;return function(i,r=e){const{canvasPos:n,origin:a,direction:c,snapRadius:u,snapToVertex:p,snapToEdge:f}=i;if(!p&&!f)return this.pick({canvasPos:n,pickSurface:!0});const m=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickZNear=t.camera.project.near,s.pickZFar=t.camera.project.far;const g=u||30,_=x.getRenderBuffer(`uniquePickColors-aabs-${g}`,{depthTexture:!0,size:[2*g+1,2*g+1]});s.snapVectorA=[n?D(n[0]*m,o.drawingBufferWidth):0,n?S(n[1]*m,o.drawingBufferHeight):0],s.snapInvVectorAB=[o.drawingBufferWidth/(2*g),o.drawingBufferHeight/(2*g)],_.bind(o.RGBA32I,o.RGBA32I,o.RGBA8UI),o.viewport(0,0,_.size[0],_.size[1]),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.disable(o.CULL_FACE),o.depthMask(!0),o.disable(o.BLEND),o.depthFunc(o.LEQUAL),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),o.clearBufferiv(o.COLOR,1,new Int32Array([0,0,0,0])),o.clearBufferuiv(o.COLOR,2,new Uint32Array([0,0,0,0])),s.pickViewMatrix=n?t.camera.viewMatrix:h.lookAtMat4v(a,h.addVec3(a,c,h.vec3()),h.vec3([0,1,0]),h.mat4());const v=t.camera.projMatrix;for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(s.pickViewMatrix,v)}}o.drawBuffers([o.COLOR_ATTACHMENT0,o.COLOR_ATTACHMENT1,o.COLOR_ATTACHMENT2]);const b=function(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(let t=0,i=d.length;t<i;t++){const i=d[t];i.drawSnapInit&&!i.culled&&i.visible&&i.pickable&&i.drawSnapInit(e)}return e.snapPickLayerParams}(s),y=[];s.snapPickLayerParams=y,o.depthMask(!1),o.drawBuffers([o.COLOR_ATTACHMENT0]),p&&f?(s.snapMode="edge",T(s),s.snapMode="vertex",s.snapPickLayerNumber++,T(s)):(s.snapMode=p?"vertex":"edge",T(s)),o.depthMask(!0);const w=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4),B=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4,1),P=_.readArray(o.RGBA_INTEGER,o.UNSIGNED_INT,Uint32Array,4,2);_.unbind();let C=null,M=null,F=null;const E=4*g+g*_.size[0]*4,I=w.slice(E,E+4),R=B.slice(E,E+4),U=P.slice(E,E+4);if(0!==I[3]){const e=b[Math.abs(I[3])%b.length],t=e.origin,i=e.coordinateScale;C=[I[0]*i[0]+t[0],I[1]*i[1]+t[1],I[2]*i[2]+t[2]],M=h.normalizeVec3([R[0]/h.MAX_INT,R[1]/h.MAX_INT,R[2]/h.MAX_INT]);const s=U[0]+(U[1]<<8)+(U[2]<<16)+(U[3]<<24);F=l.items[s]}let L=[];for(let e=0;e<w.length;e+=4)if(w[e+3]>0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));L.push({x:s,y:r,dist:o,isVertex:p&&f?w[e+3]>y.length/2:p,result:[w[e+0],w[e+1],w[e+2],w[e+3]],normal:[B[e+0],B[e+1],B[e+2],B[e+3]],id:[P[e+0],P[e+1],P[e+2],P[e+3]]})}let k=null,O=null,N=null,V=null;if(L.length>0){L.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),V=L[0].isVertex?"vertex":"edge";const e=L[0].result,t=L[0].normal,i=L[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;O=h.normalizeVec3([t[0]/h.MAX_INT,t[1]/h.MAX_INT,t[2]/h.MAX_INT]),k=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==k)return null;let Q=null;null!==k&&(Q=t.camera.projectWorldPos(k));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&F&&(F=F.delegatePickedEntity?F.delegatePickedEntity():F),r.reset(),r.snappedToEdge="edge"===V,r.snappedToVertex="vertex"===V,r.worldPos=k||C,r.worldNormal=O||M,r.entity=H||F,r.canvasPos=n||t.camera.projectWorldPos(C||k),r.snappedCanvasPos=Q||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new VA(t,x),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){F(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=d.length;e<t;e++){const t=d[e];t.drawOcclusion&&!0!==t.culled&&!1!==t.visible&&!1!==t.pickable&&t.drawOcclusion(s)}this._occlusionTester.drawMarkers(s),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,s){const r=x.getRenderBuffer("snapshot");let o,n,a,l;for(r.bind(),r.clear(),this.render({force:!0,opaqueOnly:s}),n=0;n<i;n++)a=2*n,l=4*n,o=r.read(e[a],e[a+1]),t[l]=o[0],t[l+1]=o[1],t[l+2]=o[2],t[l+3]=o[3];r.unbind(),_=!0},this.beginSnapshot=function(e={}){const t=x.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),P=!0},this.renderSnapshot=function(){if(!P)return;x.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),_=!0},this.readSnapshot=function(e){return x.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return x.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){if(!P)return;x.getRenderBuffer("snapshot").unbind(),P=!1},this.destroy=function(){A={},c={},x.destroy(),C.destroy(),M.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class $A extends T{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.MOUSE_LEFT_BUTTON=260,this.MOUSE_MIDDLE_BUTTON=261,this.MOUSE_RIGHT_BUTTON=262,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())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!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("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){const t=e.target.getBoundingClientRect();this.mouseCanvasPos[0]=e.clientX-t.left,this.mouseCanvasPos[1]=e.clientY-t.top}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()}}class ec extends T{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new ie({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],i=e[3];this._state.boundary=[0,0,t,i],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 tc extends T{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),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],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),h.perspectiveMat4(s*(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:1e4;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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ic extends T{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),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,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),h.orthoMat4c(n,a,A,l,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:1e4;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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class sc extends T{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class rc extends T{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const oc=h.vec3(),nc=h.vec3(),ac=h.vec3(),lc=h.vec3(),Ac=h.vec3(),cc=h.vec3(),hc=h.vec4(),uc=h.vec4(),dc=h.vec4(),pc=h.mat4(),fc=h.mat4(),mc=h.vec3(),gc=h.vec3(),_c=h.vec3(),vc=h.vec3();class bc extends T{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new ie({offsetEyeFromLook:!0,deviceMatrix:h.mat4(),hasDeviceMatrix:!1,matrix:h.mat4(),normalMatrix:h.mat4(),inverseMatrix:h.mat4()}),this._perspective=new tc(this),this._ortho=new ic(this),this._frustum=new sc(this),this._customProjection=new rc(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&&this._state.offsetEyeFromLook?(h.subVec3(this._eye,this._look,mc),h.normalizeVec3(mc,gc),h.mulVec3Scalar(gc,1e3,_c),h.addVec3(this._look,_c,vc),t=vc):t=this._eye,e.hasDeviceMatrix?(h.lookAtMat4v(t,this._look,this._up,fc),h.mulMat4(e.deviceMatrix,fc,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,oc);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pc),t=h.transformPoint3(pc,t,nc),this.eye=h.addVec3(this._look,t,ac),this.up=h.transformPoint3(pc,this._up,lc)}orbitPitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._eye,this._look,oc);const i=h.cross3Vec3(h.normalizeVec3(t,nc),h.normalizeVec3(this._up,ac));h.rotationMat4v(.0174532925*e,i,pc),t=h.transformPoint3(pc,t,lc),this.up=h.transformPoint3(pc,this._up,Ac),this.eye=h.addVec3(t,this._look,cc)}yaw(e){let t=h.subVec3(this._look,this._eye,oc);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pc),t=h.transformPoint3(pc,t,nc),this.look=h.addVec3(t,this._eye,ac),this._gimbalLock&&(this.up=h.transformPoint3(pc,this._up,lc))}pitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._look,this._eye,oc);const i=h.cross3Vec3(h.normalizeVec3(t,nc),h.normalizeVec3(this._up,ac));h.rotationMat4v(.0174532925*e,i,pc),this.up=h.transformPoint3(pc,this._up,cc),t=h.transformPoint3(pc,t,lc),this.look=h.addVec3(t,this._eye,Ac)}pan(e){const t=h.subVec3(this._eye,this._look,oc),i=[0,0,0];let s;if(0!==e[0]){const r=h.cross3Vec3(h.normalizeVec3(t,[]),h.normalizeVec3(this._up,nc));s=h.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=h.mulVec3Scalar(h.normalizeVec3(this._up,ac),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=h.mulVec3Scalar(h.normalizeVec3(t,lc),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=h.addVec3(this._eye,i,Ac),this.look=h.addVec3(this._look,i,cc)}zoom(e){const t=h.subVec3(this._eye,this._look,oc),i=Math.abs(h.lenVec3(t,nc)),s=Math.abs(i+e);if(s<.5)return;const r=h.normalizeVec3(t,ac);this.eye=h.addVec3(this._look,h.mulVec3Scalar(r,s),lc)}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,oc))}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}get offsetEyeFromLook(){return this._state.offsetEyeFromLook}set offsetEyeFromLook(e){this._state.offsetEyeFromLook=e,this._needUpdate(0)}projectWorldPos(e){const t=hc,i=uc,s=dc;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,h.mulMat4v4(this.viewMatrix,t,i),h.mulMat4v4(this.projMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}const yc={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 wc extends T{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 yc}set units(e){e||(e="meters");yc[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 Bc extends T{constructor(e,t={}){super(e,t),this._supported=st.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()}}class xc extends T{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const Pc={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Cc extends Xt{get type(){return"PointsMaterial"}get presets(){return Pc}constructor(e,t={}){super(e,t),this._state=new ie({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=Pc[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(Pc).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 Mc={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Fc extends Xt{get type(){return"LinesMaterial"}get presets(){return Mc}constructor(e,t={}){super(e,t),this._state=new ie({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=Mc[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Mc).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ec(e,t,i=2){const s=t&&t.length,r=s?t[0]*i:e.length;let o=Ic(e,0,r,i,!0);const n=[];if(!o||o.next===o.prev)return n;let a,l,A;if(s&&(o=function(e,t,i,s){const r=[];for(let i=0,o=t.length;i<o;i++){const n=Ic(e,t[i]*s,i<o-1?t[i+1]*s:e.length,s,!1);n===n.next&&(n.steiner=!0),r.push(Qc(n))}r.sort(kc);for(let e=0;e<r.length;e++)i=Oc(r[e],i);return i}(e,t,o,i)),e.length>80*i){a=1/0,l=1/0;let t=-1/0,s=-1/0;for(let o=i;o<r;o+=i){const i=e[o],r=e[o+1];i<a&&(a=i),r<l&&(l=r),i>t&&(t=i),r>s&&(s=r)}A=Math.max(t-a,s-l),A=0!==A?32767/A:0}return Dc(o,n,i,a,l,A,0),n}function Ic(e,t,i,s,r){let o;if(r===function(e,t,i,s){let r=0;for(let o=t,n=i-s;o<i;o+=s)r+=(e[n]-e[o])*(e[o+1]+e[n+1]),n=o;return r}(e,t,i,s)>0)for(let r=t;r<i;r+=s)o=qc(r/s|0,e[r],e[r+1],o);else for(let r=i-s;r>=t;r-=s)o=qc(r/s|0,e[r],e[r+1],o);return o&&Wc(o,o.next)&&($c(o),o=o.next),o}function Tc(e,t){if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!Wc(s,s.next)&&0!==zc(s.prev,s,s.next))s=s.next;else{if($c(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t}function Dc(e,t,i,s,r,o,n){if(!e)return;!n&&o&&function(e,t,i,s){let r=e;do{0===r.z&&(r.z=Vc(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,i=1;do{let s,r=e;e=null;let o=null;for(t=0;r;){t++;let n=r,a=0;for(let e=0;e<i&&(a++,n=n.nextZ,n);e++);let l=i;for(;a>0||l>0&&n;)0!==a&&(0===l||!n||r.z<=n.z)?(s=r,r=r.nextZ,a--):(s=n,n=n.nextZ,l--),o?o.nextZ=s:e=s,s.prevZ=o,o=s;r=n}o.nextZ=null,i*=2}while(t>1)}(r)}(e,s,r,o);let a=e;for(;e.prev!==e.next;){const l=e.prev,A=e.next;if(o?Rc(e,s,r,o):Sc(e))t.push(l.i,e.i,A.i),$c(e),e=A.next,a=A.next;else if((e=A)===a){n?1===n?Dc(e=Uc(Tc(e),t),t,i,s,r,o,2):2===n&&Lc(e,t,i,s,r,o):Dc(Tc(e),t,i,s,r,o,1);break}}}function Sc(e){const t=e.prev,i=e,s=e.next;if(zc(t,i,s)>=0)return!1;const r=t.x,o=i.x,n=s.x,a=t.y,l=i.y,A=s.y,c=Math.min(r,o,n),h=Math.min(a,l,A),u=Math.max(r,o,n),d=Math.max(a,l,A);let p=s.next;for(;p!==t;){if(p.x>=c&&p.x<=u&&p.y>=h&&p.y<=d&&Gc(r,a,o,l,n,A,p.x,p.y)&&zc(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function Rc(e,t,i,s){const r=e.prev,o=e,n=e.next;if(zc(r,o,n)>=0)return!1;const a=r.x,l=o.x,A=n.x,c=r.y,h=o.y,u=n.y,d=Math.min(a,l,A),p=Math.min(c,h,u),f=Math.max(a,l,A),m=Math.max(c,h,u),g=Vc(d,p,t,i,s),_=Vc(f,m,t,i,s);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=g&&b&&b.z<=_;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&Gc(a,c,l,h,A,u,v.x,v.y)&&zc(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&Gc(a,c,l,h,A,u,b.x,b.y)&&zc(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=g;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&Gc(a,c,l,h,A,u,v.x,v.y)&&zc(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=_;){if(b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&Gc(a,c,l,h,A,u,b.x,b.y)&&zc(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Uc(e,t){let i=e;do{const s=i.prev,r=i.next.next;!Wc(s,r)&&Xc(s,i,i.next,r)&&Jc(s,r)&&Jc(r,s)&&(t.push(s.i,i.i,r.i),$c(i),$c(i.next),i=e=r),i=i.next}while(i!==e);return Tc(i)}function Lc(e,t,i,s,r,o){let n=e;do{let e=n.next.next;for(;e!==n.prev;){if(n.i!==e.i&&jc(n,e)){let a=Yc(n,e);return n=Tc(n,n.next),a=Tc(a,a.next),Dc(n,t,i,s,r,o,0),void Dc(a,t,i,s,r,o,0)}e=e.next}n=n.next}while(n!==e)}function kc(e,t){let i=e.x-t.x;if(0===i&&(i=e.y-t.y,0===i)){i=(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)}return i}function Oc(e,t){const i=function(e,t){let i=t;const s=e.x,r=e.y;let o,n=-1/0;if(Wc(e,i))return i;do{if(Wc(e,i.next))return i.next;if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const e=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>n&&(n=e,o=i.x<i.next.x?i:i.next,e===s))return o}i=i.next}while(i!==t);if(!o)return null;const a=o,l=o.x,A=o.y;let c=1/0;i=o;do{if(s>=i.x&&i.x>=l&&s!==i.x&&Hc(r<A?s:n,r,l,A,r<A?n:s,r,i.x,i.y)){const t=Math.abs(r-i.y)/(s-i.x);Jc(i,e)&&(t<c||t===c&&(i.x>o.x||i.x===o.x&&Nc(o,i)))&&(o=i,c=t)}i=i.next}while(i!==a);return o}(e,t);if(!i)return t;const s=Yc(i,e);return Tc(s,s.next),Tc(i,i.next)}function Nc(e,t){return zc(e.prev,e,t.prev)<0&&zc(t.next,e,e.next)<0}function Vc(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-s)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Qc(e){let t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function Hc(e,t,i,s,r,o,n,a){return(r-n)*(t-a)>=(e-n)*(o-a)&&(e-n)*(s-a)>=(i-n)*(t-a)&&(i-n)*(o-a)>=(r-n)*(s-a)}function Gc(e,t,i,s,r,o,n,a){return!(e===n&&t===a)&&Hc(e,t,i,s,r,o,n,a)}function jc(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Xc(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Jc(e,t)&&Jc(t,e)&&function(e,t){let i=e,s=!1;const r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(zc(e.prev,e,t.prev)||zc(e,t.prev,t))||Wc(e,t)&&zc(e.prev,e,e.next)>0&&zc(t.prev,t,t.next)>0)}function zc(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Wc(e,t){return e.x===t.x&&e.y===t.y}function Xc(e,t,i,s){const r=Zc(zc(e,t,i)),o=Zc(zc(e,t,s)),n=Zc(zc(i,s,e)),a=Zc(zc(i,s,t));return r!==o&&n!==a||(!(0!==r||!Kc(e,i,t))||(!(0!==o||!Kc(e,s,t))||(!(0!==n||!Kc(i,e,s))||!(0!==a||!Kc(i,t,s)))))}function Kc(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Zc(e){return e>0?1:e<0?-1:0}function Jc(e,t){return zc(e.prev,e,e.next)<0?zc(e,t,e.next)>=0&&zc(e,e.prev,t)>=0:zc(e,t,e.prev)<0||zc(e,e.next,t)<0}function Yc(e,t){const i=eh(e.i,e.x,e.y),s=eh(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function qc(e,t,i,s){const r=eh(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function $c(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function eh(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const th=[0,1,0],ih=[1,0,0],sh=h.vec3(),rh=h.vec3(),oh=h.vec3(),nh=h.vec3(),ah=h.vec3();function lh(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6&&Math.abs(e[2]-t[2])<1e-6}class Ah{constructor(e){this.scene=e,this._resourcesAllocated=!1}_onCapMaterialUpdated(e,t){if(!this._resourcesAllocated){this._resourcesAllocated=!0,this._sectionPlanes=[],this._sceneModelsData={},this._dirtyMap={},this._prevIntersectionModelsMap={},this._sectionPlaneTimeout=null,this._updateTimeout=null;const e=e=>{const t=()=>{this._setAllDirty(!0),this._update()};this._sectionPlanes.push(e),e.on("pos",t),e.on("dir",t),e.on("active",t),e.once("destroyed",(()=>{const t=e.id;t&&(this._sectionPlanes=this._sectionPlanes.filter((e=>e.id!==t)),this._update())}).bind(this))};for(const t in this.scene.sectionPlanes)e(this.scene.sectionPlanes[t]);this._onSectionPlaneCreated=this.scene.on("sectionPlaneCreated",e),this._onTick=this.scene.on("tick",(()=>{let e=!1;for(const t in this._sceneModelsData)this.scene.models[t]?this._sceneModelsData[t].visible!==!!this.scene.models[t].visible&&(this._sceneModelsData[t].visible=!!this.scene.models[t].visible,e=!0):(delete this._sceneModelsData[t],e=!0);e&&this._update()}))}this._dirtyMap[t]||(this._dirtyMap[t]=new Map),this._dirtyMap[t].set(e,!0),this._update()}_update(){clearTimeout(this._updateTimeout),this._deletePreviousModels(),this._updateTimeout=setTimeout((()=>{clearTimeout(this._updateTimeout);const e=Object.values(this.scene.models).filter((e=>e.visible));this._addHatches(e,this._sectionPlanes.filter((e=>e.active))),this._setAllDirty(!1)}),100)}_setAllDirty(e){for(const t in this._dirty)this._dirtyMap[t].forEach(((i,s)=>this._dirtyMap[t].set(s,e)))}_addHatches(e,t){t.forEach((t=>{e.forEach((e=>{if(!this._doesPlaneIntersectBoundingBox(e.aabb,t))return;if(!this._dirtyMap[e.id])return;const i=new Map,s=e.objects,r=[h.vec3(),h.vec3(),h.vec3()];this._dirtyMap[e.id].forEach(((o,n)=>{if(!o)return;const a=s[n];if(!this._doesPlaneIntersectBoundingBox(a.aabb,t))return;if(!this._sceneModelsData[e.id]){const t=e.aabb;this._sceneModelsData[e.id]={verticesMap:new Map,indicesMap:new Map,modelOrigin:h.vec3([(t[0]+t[3])/2,(t[1]+t[4])/2,(t[2]+t[5])/2])}}const l=this._sceneModelsData[e.id],A=l.modelOrigin;if(!l.verticesMap.has(n)){const e=a.meshes[0].isSolid(),t=[],i=[];e&&a.capMaterial&&(a.getEachVertex((e=>t.push(e[0]-A[0],e[1]-A[1],e[2]-A[2]))),a.getEachIndex((e=>i.push(e)))),l.verticesMap.set(n,t),l.indicesMap.set(n,i)}const c=l.verticesMap.get(n),u=l.indicesMap.get(n),d=-h.dotVec3(h.subVec3(t.pos,A,sh),t.dir),p=[],f=u.length;for(let e=0;e<f;e+=3){for(let t=0;t<3;t++){const i=3*u[e+t];r[t][0]=c[i],r[t][1]=c[i+1],r[t][2]=c[i+2]}if(!r[0][0]&&!r[0][1]&&!r[0][2])continue;const i=[];for(let e=0;e<3;e++){const s=r[e],o=r[(e+1)%3],n=d+h.dotVec3(t.dir,s),a=d+h.dotVec3(t.dir,o);if(n*a>0)continue;const l=-n/(a-n);i.push(h.lerpVec3(l,0,1,s,o,h.vec3()))}2===i.length&&p.push(i)}p.length>0&&i.set(n,p)}));const o=new Map;i.forEach(((e,t)=>{o.set(t,[[e[0]]]),e.splice(0,1);let s=0;for(;e.length>0;){const r=o.get(t)[s][o.get(t)[s].length-1][1];let n=!1;for(let i=0;i<e.length;i++){const[a,l]=e[i];if(lh(r,a)){o.get(t)[s].push(e[i]),e.splice(i,1),n=!0;break}if(lh(r,l)){o.get(t)[s].push([l,a]),e.splice(i,1),n=!0;break}}if(!n&&lh(r,o.get(t)[s][0][0])&&e.length>1)o.get(t).push([i.get(t)[0]]),e.splice(0,1),s++;else if(!n)break}}));const n=new Map;o.forEach(((e,i)=>{const s=[];for(let i=0;i<e.length;i++)s.push([]),e[i].forEach((e=>{s[i].push([this._projectTo2D(e[0],t.dir),this._projectTo2D(e[1],t.dir)])}));n.set(i,s)}));const a=new Map;let l;n.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin;l=[];const o=i,n=[],A=new Set;for(let e=0;e<o.length;e++){if(A.has(e))continue;const t=[o[e]];A.add(e);for(let i=e+1;i<o.length;i++)A.has(i)||(this._isLoopInside(o[e],o[i])||this._isLoopInside(o[i],o[e]))&&(t.push(o[i]),A.add(i));n.push(t)}n.forEach((e=>{const i=[],s=[];let o=0;const n=e.map((e=>{let t=0;for(let i=0;i<e.length;i++){const s=(i+1)%e.length;t+=e[i][0][0]*e[s][0][1],t-=e[s][0][0]*e[i][0][1]}return Math.abs(t)/2})),a=n.indexOf(Math.max(...n));e[a].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2}));for(let t=0;t<e.length;t++)t!==a&&(s.push(o/2),e[t].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2})));const A=Ec(i,s),c=[];for(let e=0;e<A.length;e+=3){const s=[];for(let o=0;o<3;o++){const n=2*A[e+o],a=[i[n],i[n+1]],l=this._convertTo3D(a,t,r);s.push(l)}c.push(s)}l.push(c)})),a.set(s,l)}));const A=new Map;a.forEach(((e,t)=>{l=[],e.forEach((e=>{const t=new Map,i=[],s=[];let r=0;e.forEach((e=>{const o=[];e.forEach((e=>{const s=`${e[0].toFixed(6)},${e[1].toFixed(6)},${e[2].toFixed(6)}`;t.has(s)?o.push(t.get(s)):(i.push(e[0],e[1],e[2]),t.set(s,r),o.push(r),r++)})),s.push(...o)})),l.push({positions:i,indices:s})})),A.set(t,l)})),this._prevIntersectionModelsMap[e.id]||(this._prevIntersectionModelsMap[e.id]=new Map),h.mulVec3Scalar(t.dir,.001,ah),A.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin,o=new Array(i.size);let n=0;i.forEach(((i,a)=>{const l=i.positions,A=i.indices;l.length;const c=h.buildNormals(l,A),u=this._createUVs(l,t,r);o[n++]=new zt(this.scene,{id:`${t.id}-${s}-${a}`,geometry:new pe(this.scene,{primitive:"triangles",positions:l,indices:A,normals:c,uv:u}),origin:h.addVec3(r,ah,sh),position:[0,0,0],rotation:[0,0,0],material:e.objects[s].capMaterial})})),this._prevIntersectionModelsMap[e.id].has(s)?this._prevIntersectionModelsMap[e.id].get(s).push(...o):this._prevIntersectionModelsMap[e.id].set(s,o)}))}))}))}_doesPlaneIntersectBoundingBox(e,t){const i=[e[0],e[1],e[2]],s=[e[3],e[4],e[5]],r=[[i[0],i[1],i[2]],[s[0],i[1],i[2]],[i[0],s[1],i[2]],[s[0],s[1],i[2]],[i[0],i[1],s[2]],[s[0],i[1],s[2]],[i[0],s[1],s[2]],[s[0],s[1],s[2]]];let o=!1,n=!1;for(const e of r){const i=t.dist+h.dotVec3(t.dir,e);if(i>0&&(o=!0),i<0&&(n=!0),o&&n)return!0}return!1}_buildLines(e){for(const t in e)for(let i=0;i<e[t].length;i++){const s=e[t][i];s.length<=0||s.forEach(((e,t)=>{new zt(this.scene,{clippable:!1,geometry:new pe(this.scene,Ee({startPoint:e[0],endPoint:e[1]})),material:new Jt(this.scene,{emissive:[1,0,0]})})}))}}_projectTo2D(e,t){let i;i=Math.abs(t[0])>Math.abs(t[1])?[-t[2],0,t[0]]:[0,t[2],-t[1]],i=h.normalizeVec3(i);const s=h.vec3(t),r=h.cross3Vec3(s,i),o=h.normalizeVec3(r);return[h.dotVec3(e,i),h.dotVec3(e,o)]}_isLoopInside(e,t){const i=e[0][0];let s=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){const o=t[e][0][0],n=t[e][0][1],a=t[r][0][0],l=t[r][0][1];n>i[1]!=l>i[1]&&i[0]<(a-o)*(i[1]-n)/(l-n)+o&&(s=!s)}return s}_convertTo3D(e,t,i){let s,r=t.dir,o=t.pos;s=Math.abs(r[0])>Math.abs(r[1])?[-r[2],0,r[0]]:[0,r[2],-r[1]],s=h.normalizeVec3(s);const n=h.vec3(r),a=h.cross3Vec3(n,s),l=h.normalizeVec3(a),A=e[0],c=e[1],u=[s[0]*A+l[0]*c,s[1]*A+l[1]*c,s[2]*A+l[2]*c],d=h.dotVec3(r,[o[0]-u[0]-i[0],o[1]-u[1]-i[1],o[2]-u[2]-i[2]]);return[u[0]+r[0]*d,u[1]+r[1]*d,u[2]+r[2]*d]}_deletePreviousModels(){for(const e in this._prevIntersectionModelsMap){this._prevIntersectionModelsMap[e].forEach(((t,i)=>{this._dirtyMap[e].get(i)&&(t.forEach((e=>{e.destroy()})),this._prevIntersectionModelsMap[e].delete(i))})),this._prevIntersectionModelsMap[e].size<=0&&delete this._prevIntersectionModelsMap[e]}}_createUVs(e,t,i){const s=t.pos,r=sh;r.set(t.dir),h.normalizeVec3(r);const o=rh,n=[];for(let t=0;t<e.length;t+=3){o[0]=e[t]+i[0],o[1]=e[t+1]+i[1],o[2]=e[t+2]+i[2];const a=h.subVec3(o,s,oh),l=h.dotVec3(a,r);h.subVec3(o,h.mulVec3Scalar(r,l,oh),o);const A=Math.abs(h.dotVec3(r,th))<.999?h.cross3Vec3(r,th,oh):ih,c=h.cross3Vec3(r,A,oh);h.normalizeVec3(c,c);const u=h.subVec3(o,s,o);n.push(h.dotVec3(u,h.normalizeVec3(h.cross3Vec3(c,r,nh))),h.dotVec3(u,c))}return n}destroy(){this._deletePreviousModels(),this._resourcesAllocated&&(this.scene.off(this._onModelLoaded),this.scene.off(this._onModelUnloaded),this.scene.off(this._onSectionPlaneCreated),this.scene.off(this._onTick))}}function ch(e,t){const i={};let s,r;for(let o=0,n=t.length;o<n;o++)s=t[o],r=e.components[s],r?r.isEntity?i[s]=!0:e.warn("pick(): Component is not an Entity: "+s):e.warn("pick(): Component not found: "+s);return i}class hh extends T{get type(){return"Scene"}constructor(e,t={}){super(null,t);const i=t.canvasElement||document.querySelector(`#${t.canvasId}`);if(!(i instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";this._tickifiedFunctions={};const s=!!t.transparent,r=!!t.alphaDepthMask;this._aabbDirty=!0,this._readableGeometry=!!t.readableGeometryEnabled,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 UA(this,{dontClear:!0,canvas:i,spinnerElementId:t.spinnerElementId,transparent:s,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 qA(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;e<s;e++)i.push("cp");return i.push(";"),e=i.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let i=0,s=this.sectionPlanes.length;i<s;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)},this.setNumCachedSectionPlanes=function(t){this._numCachedSectionPlanes=t,e=null},this.getNumCachedSectionPlanes=function(){return this._numCachedSectionPlanes},this.getNumAllocatedSectionPlanes=function(){const e=this.sectionPlanes.length;return e>this._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=h.vec4([0,0,0,0]),t=h.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i<r;i++)s=t[i],e.push("/"),e.push(s.type),e.push("world"===s.space?"w":"v"),s.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t<r;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),s&&s.id===e.id&&(s=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(let t=0,s=this.reflectionMaps.length;t<s;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(let t=0,s=this.lightMaps.length;t<s;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!s)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){s=t;break}}if(s){const e=s.color,i=s.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i,t}return e}},this.input=new $A(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new wc(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Bc(this,{enabled:t.saoEnabled}),this.crossSections=new xc(this,{}),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,this._markerZOffset=t.markerZOffset,M._addScene(this),this._initDefaults(),this._viewport=new ec(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new bc(this,{id:"default.camera",dontClear:!0}),this._sectionCaps=new Ah(this),new AA(this,{color:[1,1,1],intensity:.7}),new hA(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new hA(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 "+_.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 i=this.types[e.type];i||(i=this.types[t]={}),i[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,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],_.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_capMaterialUpdated(e,t){this._sectionCaps._onCapMaterialUpdated(e,t)}_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)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_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)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_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)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){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}_deRegisterOpacityObject(e){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}_deRegisterOffsetObject(e){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 i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}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}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.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 i=this._passes,s=this._clearEachPass;let r,o;for(r=0;r<i;r++)t.pass=r,this.fire("rendering",t,!0),o=s||0===r,this._renderer.render({pass:r,clear:o,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}compile(){this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1)}_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:(!_.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:(!_.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:(!_.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"]||ve(pe)}get material(){return this.components["default.material"]||new Jt(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new vi(this,{id:"default.xrayMaterial",fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new vi(this,{id:"default.highlightMaterial",fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new vi(this,{id:"default.selectedMaterial",fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new yi(this,{id:"default.edgeMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Cc(this,{id:"default.pointsMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new Fc(this,{id:"default.linesMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){const e=this.aabb;this._center||(this._center=h.vec3()),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,i=h.MAX_DOUBLE,s=h.MAX_DOUBLE,r=h.MIN_DOUBLE,o=h.MIN_DOUBLE,n=h.MIN_DOUBLE;const a=this._collidables;let l,A=!1;for(const c in a)if(a.hasOwnProperty(c)){if(l=a[c],!1===l.collidable)continue;e=l.aabb,e[0]<t&&(t=e[0]),e[1]<i&&(i=e[1]),e[2]<s&&(s=e[2]),e[3]>r&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}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 i=e.includeEntities||e.include;i&&(e.includeEntityIds=ch(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=ch(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}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,i=e.length;t<i;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,i=e.length;t<i;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,i=e.length;t<i;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(_.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,i=h.MAX_DOUBLE,s=h.MAX_DOUBLE,r=h.MAX_DOUBLE,o=h.MIN_DOUBLE,n=h.MIN_DOUBLE,a=h.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const l=e.aabb;l[0]<i&&(i=l[0]),l[1]<s&&(s=l[1]),l[2]<r&&(r=l[2]),l[3]>o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=h.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let o=this.objects[r];if(o)i=t(o)||i;else{const e=this.modelIds;for(let s=0,n=e.length;s<n;s++){const n=e[s],a=h.globalizeObjectId(n,r);o=this.objects[a],o&&(i=t(o)||i)}}}return i}tickify(e){const t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;let i,s=0,r=0;const o=function(...e){i=e,r++},n=this.on("tick",(()=>{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this._sectionCaps.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._sectionCaps=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const uh=h.vec4(),dh=h.vec4(),ph=h.vec3(),fh=h.vec3(),mh=h.vec3(),gh=h.vec4(),_h=h.vec4(),vh=h.vec4();class bh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=h.subVec3(e,r.eye,ph);s=h.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,gh),o=h.subVec3(s,r.eye,vh),n=h.mulVec3Scalar(h.normalizeVec3(o),-i,[]);if(r.eye=[r.eye[0]-n[0],r.eye[1]-n[1],r.eye[2]-n[2]],r.look=[r.look[0]-n[0],r.look[1]-n[1],r.look[2]-n[2]],e){const t=h.subVec3(e,r.eye,ph),i=h.lenVec3(t),s=h.mulVec3Scalar(h.normalizeVec3(h.subVec3(r.look,r.eye,fh)),i);r.look=[r.eye[0]+s[0],r.eye[1]+s[1],r.eye[2]+s[2]]}}else if("ortho"===r.projection){const e=this._unproject(t,gh);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,_h),o=h.subVec3(s,e,vh),n=h.mulVec3Scalar(h.normalizeVec3(h.subVec3(r.look,r.eye,ph)),-i,fh),a=h.addVec3(o,n,mh);r.eye=[r.eye[0]-a[0],r.eye[1]-a[1],r.eye[2]-a[2]],r.look=[r.look[0]-a[0],r.look[1]-a[1],r.look[2]-a[2]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=h.dotVec4(n,r)/h.dotVec4(n,o);return i.project.unproject(e,a,uh,dh,t),t}destroy(){}}const yh=h.vec3(),wh=h.vec3(),Bh=h.vec3(),xh=h.vec4(),Ph=h.vec4(),Ch=h.vec4(),Mh=Math.PI-.001;class Fh{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=h.vec3(),this._cameraOffset=h.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=h.vec3(),this._rtcPos=h.vec3(),this._pivotViewPos=h.vec4(),this._pivotProjPos=h.vec4(),this._pivotCanvasPos=h.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=h.vec3();h.decomposeMat4(h.inverseMat4(this._scene.viewer.camera.viewMatrix,h.mat4()),t,h.vec4(),h.vec3());const i=h.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),Ge(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new ge(this._scene,xe({radius:s})),this._pivotSphere=new zt(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){h.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,h.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(Ge(this.getPivotPos(),this._rtcCenter,this._rtcPos),h.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Jt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){const e=this._scene.camera;let t=h.lookAtMat4v(e.eye,e.look,e.up);h.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=h.distVec3(e.eye,i),t=h.inverseMat4(t);const s=h.transformVec3(t,this._cameraOffset),r=h.vec3();if(h.subVec3(e.eye,i,r),h.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=h.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=h.normalizeVec3(h.subVec3(e.look,e.eye,yh)),i=h.cross3Vec3(t,e.worldUp,wh);return h.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(h.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=h.dotVec4(n,r)/h.dotVec4(n,o),l=xh;t.project.unproject(e,a,Ph,Ch,l);const A=h.normalizeVec3(h.subVec3(l,t.eye,yh)),c=h.addVec3(t.eye,h.mulVec3Scalar(A,i,wh),Bh);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s;const o=r<0,n=r>0,a=Math.abs(this._polar-.001)<.005,l=Math.abs(this._polar-Mh)<.005;let A=this._polar+.01*r;A=a&&o?.001:l&&n?Mh:h.clamp(A,.001,Mh),this._polar=A;const c=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=c[1];c[1]=c[2],c[2]=e}const u=h.lenVec3(h.subVec3(i.look,i.eye,h.vec3())),d=this.getPivotPos();h.addVec3(c,d);let p=h.lookAtMat4v(c,d,i.worldUp);p=h.inverseMat4(p);const f=h.transformVec3(p,this._cameraOffset);p[12]-=f[0],p[13]-=f[1],p[14]-=f[2];const m=[p[8],p[9],p[10]];i.eye=[p[12],p[13],p[14]],h.subVec3(i.eye,h.mulVec3Scalar(m,u),i.look),i.up=[p[4],p[5],p[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Eh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=h.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new IA;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Ih=h.vec2();class Th{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a,l,A,c=0,u=0,d=0,p=0,f=!1;const m=h.vec3();let g=!0;const _=this._scene.canvas.canvas,v=[];function b(e=!0){c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],d=s.pointerCanvasPos[0],p=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(f=!0,m.set(o.pickResult.worldPos)):f=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!1}),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{v.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{v.splice(0)}),_.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:v[e.input.KEY_SHIFT]||i.planView?(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b()):(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b(!1));break;case 2:l=!0,v[e.input.MOUSE_MIDDLE_BUTTON]=!0,b();break;case 3:A=!0,v[e.input.MOUSE_RIGHT_BUTTON]=!0,i.panRightClick&&b()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!a&&!l&&!A)return;const o=e.canvas.boundary,d=o[2],p=o[3],g=s.pointerCanvasPos[0],_=s.pointerCanvasPos[1],b=i.planView||n._isKeyDownForAction(n.MOUSE_PAN,v),y=n._isKeyDownForAction(n.MOUSE_ROTATE,v),w=document.pointerLockElement?t.movementX:g-c,B=document.pointerLockElement?t.movementY:_-u;if(b){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(f?h.lenVec3(h.subVec3(m,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*w*i/p,r.panDeltaY+=1.5*B*i/p}else r.panDeltaX+=.5*t.ortho.scale*(w/p),r.panDeltaY+=.5*t.ortho.scale*(B/p)}else y&&(i.planView||(i.firstPerson?(r.rotateDeltaY-=w/d*i.dragRotationRate/2,r.rotateDeltaX+=B/p*(i.dragRotationRate/4)):(r.rotateDeltaY-=w/d*(1.5*i.dragRotationRate),r.rotateDeltaX+=B/p*(1.5*i.dragRotationRate))));c=g,u=_}),_.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:case 2:case 3:a=!1,l=!1,A=!1,v[e.input.MOUSE_LEFT_BUTTON]=!1,v[e.input.MOUSE_MIDDLE_BUTTON]=!1,v[e.input.MOUSE_RIGHT_BUTTON]=!1}}),_.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Ih);const i=Ih[0],s=Ih[1];Math.abs(i-d)<3&&Math.abs(s-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Ih,event:e},!0)}_.style.removeProperty("cursor")}}),_.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const y=1/60;let w=null;_.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel&&n._isKeyDownForAction(n.MOUSE_DOLLY,v)))return;const t=performance.now()/1e3;var o=null!==w?t-w:0;w=t,o>.05&&(o=.05),o<y&&(o=y);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const l=a/Math.abs(a);r.dollyDelta+=-l*o*i.mouseWheelDollyRate,g&&(s.followPointerDirty=!0,g=!1)},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const Dh=h.vec3(),Sh=h.vec3(),Rh=h.vec3(),Uh=h.vec3(),Lh=h.vec3(),kh={eye:h.vec3(),look:h.vec3(),up:h.vec3()};class Oh{constructor(e,t,i,s){this._scene=e;const r=t.cameraControl,o=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||c||u))return;const d=e.aabb,p=h.getAABB3Diag(d);h.getAABB3Center(d,Dh);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*h.DEGTORAD)),m=1.1*p;kh.orthoScale=m,n?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldRight,f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):a?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldForward,f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):l?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldRight,-f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):A?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldForward,-f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):c?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldUp,f,Sh),Lh)),kh.look.set(Dh),kh.up.set(h.normalizeVec3(h.mulVec3Scalar(o.worldForward,1,Rh),Uh))):u&&(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldUp,-f,Sh),Lh)),kh.look.set(Dh),kh.up.set(h.normalizeVec3(h.mulVec3Scalar(o.worldForward,-1,Rh)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Dh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(kh,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(kh),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Nh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;let l=!1,A=!1;const c=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;h.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=h.vec3(),i=h.vec3();h.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),u=a.hasSubs("hoverOff"),d=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||u||d||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});c.addEventListener("mousemove",d),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot(),this._lastClickedWorldPos=t.worldPos.slice()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):this._lastClickedWorldPos?n.setPivotPos(this._lastClickedWorldPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=h.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=h.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Vh{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[];e.canvas.canvas;let a=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{a=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,t.pivotController.getPivoting()&&t.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{n.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{n.splice(0)}),this._onTick=e.on("tick",(l=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,c=l.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=c*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),a&&(s.followPointerDirty=!0,a=!1)}}const h=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),m=A._isKeyDownForAction(A.PAN_DOWN,n),g=(n[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(h||u||d||p||f||m)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=g:f&&(r.panDeltaY+=-g),p?r.panDeltaX+=-g:d&&(r.panDeltaX+=g),u?r.panDeltaZ+=g:h&&(r.panDeltaZ+=-g))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),this._scene.input.off(this._onSceneKeyUp)}}const Qh=h.vec3();class Hh{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController,A=t.cameraControl;let c=1,u=1,d=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--c<=0&&(c=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?d=n.pickResult.worldPos:(u=1,d=null),s.followPointerDirty=!1),d){const t=Math.abs(h.lenVec3(h.subVec3(d,e.camera.eye,Qh)));u=t/i.dollyProximityThreshold}u<i.dollyMinSpeed&&(u=i.dollyMinSpeed)}}else u=1,d=null;const p=r.dollyDelta*u;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&a.getPivoting()?(a.continuePivot(r.rotateDeltaY,r.rotateDeltaX),a.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?o.pitch(-r.rotateDeltaX):o.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?o.yaw(r.rotateDeltaY):o.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t=A._cursors.rotate),Math.abs(r.panDeltaX)<.001&&(r.panDeltaX=0),Math.abs(r.panDeltaY)<.001&&(r.panDeltaY=0),Math.abs(r.panDeltaZ)<.001&&(r.panDeltaZ=0),0!==r.panDeltaX||0!==r.panDeltaY||0!==r.panDeltaZ){const e=h.vec3();let s,n;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){o.xUp?(s=o.eye[0],n=o.look[0]):o.yUp?(s=o.eye[1],n=o.look[1]):o.zUp&&(s=o.eye[2],n=o.look[2]),o.pan(e);const t=o.eye,i=o.look;o.xUp?(t[0]=s,i[0]=n):o.yUp?(t[1]=s,i[1]=n):o.zUp&&(t[2]=s,i[2]=n),o.eye=t,o.look=i}else o.pan(e);t=A._cursors.pan}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==p){if(t=p<0?A._cursors.dollyForward:A._cursors.dollyBackward,i.firstPerson){let e,t;if(i.constrainVertical&&(o.xUp?(e=o.eye[0],t=o.look[0]):o.yUp?(e=o.eye[1],t=o.look[1]):o.zUp&&(e=o.eye[2],t=o.look[2])),i.followPointer){l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p;if(i.constrainVertical){const i=o.eye,s=o.look;o.xUp?(i[0]=e,s[0]=t):o.yUp?(i[1]=e,s[1]=t):o.zUp&&(i[2]=e,s[2]=t),o.eye=i,o.look=s}}else if(i.planView)if(i.followPointer){l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);else if(i.followPointer){l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);r.dollyDelta*=i.dollyInertia}n.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class Gh{constructor(e,t,i,s,r){this._scene=e;const o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{jh(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(jh(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function jh(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const zh=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Wh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=h.vec2(),l=h.vec2(),A=h.vec2(),c=h.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(zh(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length<r.length;)u.push(h.vec2());for(let e=0,t=r.length;e<t;++e)zh(r[e],u[e]);p=r.length}),d.addEventListener("touchend",this._canvasTouchEndHandler=()=>{n.getPivoting()&&(n.endPivot(),n.hidePivot())}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],m=t.touches;if(t.touches.length===p){if(1===p){zh(m[0],l),h.subVec2(l,u[0],c);const t=c[0],o=c[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=m[0],n=m[1];zh(t,l),zh(n,A);const a=h.geometricMeanVec2(u[0],u[1]),c=h.geometricMeanVec2(l,A),p=h.vec2();h.subVec2(a,c,p);const f=p[0],g=p[1],_=e.camera,v=h.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(h.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(h.lenVec3(h.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=g*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(g/d)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<p;++e)zh(m[e],u[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}const Xh=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Kh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a;const l=[],A=new Float32Array(2);let c=-1,u=-1;const d=this._scene.canvas.canvas,p=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;h.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,Xh(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,h=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(h)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else c=-1;for(;l.length<r.length;)l.push(new Float32Array(2));for(let e=0,t=r.length;e<t;++e)Xh(r[e],l[e]);l.length=r.length},{passive:!0}),d.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(u>-1&&c-u<325?(Xh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):h.distVec2(l[0],A)<4&&(Xh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),c=-1),l.length=r.length;for(let e=0,t=r.length;e<t;++e)l[e][0]=r[e].pageX,l[e][1]=r[e].pageY},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class Zh extends T{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this.MOUSE_PAN=18,this.MOUSE_ROTATE=19,this.MOUSE_DOLLY=20,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:h.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:h.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Eh(this,this._configs),pivotController:new Fh(i,this._configs),panController:new bh(i),cameraFlight:new q(this,{duration:.5})},this._handlers=[new Gh(this.scene,this._controllers,this._configs,this._states,this._updates),new Wh(this.scene,this._controllers,this._configs,this._states,this._updates),new Th(this.scene,this._controllers,this._configs,this._states,this._updates),new Oh(this.scene,this._controllers,this._configs,this._states,this._updates),new Nh(this.scene,this._controllers,this._configs,this._states,this._updates),new Kh(this.scene,this._controllers,this._configs,this._states,this._updates),new Vh(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cursors={dollyForward:"zoom-in",dollyBackward:"zoom-out",rotate:"grabbing",pan:"move"},this._cameraUpdater=new Hh(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_areAllKeysDown(e,t){if(!t||t.length<=0)return!0;if(!e)return!1;for(let i=0,s=t.length;i<s;i++){if(!e[t[i]])return!1}return!0}_isAnyOtherKeyDown(e,t){for(let i=0,s=e.length;i<s;i++)if(e[i])if(Array.isArray(t)){if(t.indexOf(i)<0)return!0}else if(i!==t)return!0;return!1}_isMouseAction(e){switch(e){case this.MOUSE_ROTATE:case this.MOUSE_DOLLY:case this.MOUSE_PAN:return!0;default:return!1}}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;if(0===i.length&&this._isMouseAction(e))return!0;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e<s;e++){const s=i[e];if(Array.isArray(s)){if(this._areAllKeysDown(t,s)&&!this._isAnyOtherKeyDown(t,s))return!0}else if(t[s]&&!this._isAnyOtherKeyDown(t,s))return!0}return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}get active(){return this._configs.active}set snapToVertex(e){this._configs.snapToVertex=!!e}get snapToVertex(){return this._configs.snapToVertex}set snapToEdge(e){this._configs.snapToEdge=!!e}get snapToEdge(){return this._configs.snapToEdge}set snapRadius(e){e=e||30,this._configs.snapRadius=e}get snapRadius(){return this._configs.snapRadius}set keyboardEnabledOnlyIfMouseover(e){this._configs.keyboardEnabledOnlyIfMouseover=!!e}get keyboardEnabledOnlyIfMouseover(){return this._configs.keyboardEnabledOnlyIfMouseover}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}setCursorStyle(e,t){Object.prototype.hasOwnProperty.call(this._cursors,e)?this._cursors={...this._cursors,[e]:t}:console.warn(`Action '${e}' is not valid for cursor styles.`)}getCursorStyle(e){return this._cursors[e]||null}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e;const t=this._keyMap[this.MOUSE_PAN];if(t&&t.length>0){const e=this.scene.input;for(let i=0,s=t.length;i<s;i++)this._configs.panRightClick&&t[i]===e.MOUSE_MIDDLE_BUTTON?this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_RIGHT_BUTTON:this._configs.panRightClick||t[i]!==e.MOUSE_RIGHT_BUTTON||(this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_MIDDLE_BUTTON)}}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}enablePivotSphere(e={}){this._controllers.pivotController.enablePivotSphere(e)}disablePivotSphere(){this._controllers.pivotController.disablePivotSphere()}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}set doubleClickTimeFrame(e){this._configs.doubleClickTimeFrame=null!=e?e:250}get doubleClickTimeFrame(){return this._configs.doubleClickTimeFrame}set zoomOnMouseWheel(e){this._configs.zoomOnMouseWheel=!!e}get zoomOnMouseWheel(){return this._configs.zoomOnMouseWheel}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class Jh{constructor(e,t,i,s,r){this.name=e,this.type=i,this.value=t,this.valueType=s,this.description=r}}class Yh{constructor(e){if(this.id=e.id,this.originalSystemId=e.originalSystemId,this.metaModels=[],this.name=e.name,this.type=e.type,this.properties=[],e.properties){const t=e.properties;for(let e=0,i=t.length;e<i;e++){const i=t[e];Number.isInteger(i)?this.properties.push(i):this.properties.push(new Jh(i.name,i.value,i.type,i.valueType,i.description))}}}}class qh{constructor(e){this.metaModels=[],this.id=e.id,this.parentId=e.parentId,this.parent=null,this.originalSystemId=e.originalSystemId,this.name=e.name,this.type=e.type,this.propertySetIds=e.propertySetIds,this.propertySets=[],this.attributes=e.attributes||{},void 0!==e.external&&null!==e.external&&(this.external=e.external)}get metaModel(){return 1==this.metaModels.length?this.metaModels[0]:null}getObjectIDsInSubtree(){const e=[];return function t(i){if(!i)return;e.push(i.id);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this),e}withMetaObjectsInSubtree(e){!function t(i){if(!i)return;e(i);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=e[i];const r=[];return function e(i){if(!i)return;t[i.type]&&r.push(i.id);const s=i.children;if(s)for(var o=0,n=s.length;o<n;o++)e(s[o])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class $h{constructor(e){this.id=e.id,this.projectId=e.projectId,this.revisionId=e.revisionId,this.author=e.author,this.createdAt=e.createdAt,this.creatingApplication=e.creatingApplication,this.schema=e.schema,this.metaScene=e.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects={},this.graph=e.graph||{},this.metaScene.metaModels[this.id]=this,this._propertyLookup=[],this.finalized=!1}get rootMetaObject(){return 1===this.rootMetaObjects.length?this.rootMetaObjects[0]:null}loadData(e,t={}){if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);const i=this.metaScene,s=e.properties;if(s)for(let e=0,t=s.length;e<t;e++)this._propertyLookup.push(s[e]);if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.properties||(s.properties=[]);let r=i.propertySets[s.id];r||(r=new Yh({id:s.id,originalSystemId:s.originalSystemId||s.id,type:s.type,name:s.name,properties:s.properties}),i.propertySets[r.id]=r),r.metaModels.push(this),this.propertySets.push(r)}if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t],r=s.id;let o=i.metaObjects[r];if(!o){const e=s.type,t=s.originalSystemId,i=s.propertySets||s.propertySetIds;o=new qh({id:r,originalSystemId:t,parentId:s.parent,type:e,name:s.name,attributes:s.attributes,propertySetIds:i,external:s.external}),this.metaScene.metaObjects[r]=o,o.metaModels=[]}this.metaObjects[r]=o,s.parent||(this.rootMetaObjects.push(o),i.rootMetaObjects[r]=o),o.metaModels.push(this)}}_decompressProperties(e,t){const i=[];for(let s=0,r=t.length;s<r;s++){const r=t[s];if(Number.isInteger(r)){const o=e[r];o?t[s]=o:i.push(r)}}i.length>0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t<s;t++){const s=i.propertySetIds[t],r=e.propertySets[s];i.propertySets.push(r)}}for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.parentId){const t=e.metaObjects[i.parentId];t&&(i.parent=t,(t.children||(t.children=[])).push(i))}}for(let t in e.metaObjects){e.metaObjects[t].metaModels=[]}for(let t in e.metaModels){const i=e.metaModels[t];for(let e in i.metaObjects){i.metaObjects[e].metaModels.push(i)}}e.metaObjectsByType={};for(let t in e.metaObjects){const i=e.metaObjects[t],s=i.type;(e.metaObjectsByType[s]||(e.metaObjectsByType[s]={}))[t]=i}if(this.propertySets)for(let e=0,t=this.propertySets.length;e<t;e++){const t=this.propertySets[e];this._decompressProperties(this._propertyLookup,t.properties)}this._propertyLookup=[],this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}getJSON(){const e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]},t=Object.values(this.metaObjects);for(let i=0,s=t.length;i<s;i++){const s=t[i],r={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name};s.parent&&(r.parent=s.parent.id),s.attributes&&(r.attributes=s.attributes),s.propertySetIds&&(r.propertySetIds=s.propertySetIds),e.metaObjects.push(r)}for(let t=0,i=this.propertySets.length;t<i;t++){const i=this.propertySets[t],s={id:i.id,originalSystemId:i.originalSystemId,extId:i.extId,type:i.type,name:i.name,propertyies:[]};for(let e=0,t=i.properties.length;e<t;e++){const t=i.properties[e],r={id:t.id,description:t.description,type:t.type,name:t.name,value:t.value,valueType:t.valueType};s.properties.push(r)}e.propertySets.push(s)}return e}_globalizeIDs(e,t){const i=!!t.globalizeObjectIds;if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t];if(s.originalSystemId=s.id,s.parent&&(s.originalParentSystemId=s.parent),i&&(s.id=h.globalizeObjectId(this.id,s.id),s.parent&&(s.parent=h.globalizeObjectId(this.id,s.parent))),i){const e=s.propertySetIds;if(e){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(h.globalizeObjectId(this.id,e[i]));s.propertySetIds=t,s.originalSystemPropertySetIds=e}}else s.originalSystemPropertySetIds=s.propertySetIds}if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.originalSystemId=s.id,i&&(s.id=h.globalizeObjectId(this.id,s.id))}}}class eu{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}createMetaModel(e,t,i={}){const s=new $h({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return s.loadData(t),s.finalize(),s}destroyMetaModel(e){const t=this.metaModels[e];if(t){if(t.propertySets)for(let i=0,s=t.propertySets.length;i<s;i++){const s=t.propertySets[i];if(1===s.metaModels.length&&s.metaModels[0].id===e)delete this.propertySets[s.id];else{const t=[];for(let i=0,r=s.metaModels.length;i<r;i++)s.metaModels[i].id!==e&&t.push(s.metaModels[i]);s.metaModels=t}}if(t.metaObjects)for(let i in t.metaObjects){const s=t.metaObjects[i];1===s.metaModels.length&&s.metaModels[0].id===e?(delete this.metaObjects[i],s.parent||delete this.rootMetaObjects[i]):s.metaModels=s.metaModels.filter((t=>t.id!==e))}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.children&&(t.children=[]),t.propertySets&&(t.propertySets=[]),t.propertySetIds)for(let e=0,i=t.propertySetIds.length;e<i;e++){const i=t.propertySetIds[e],s=this.propertySets[i];t.propertySets.push(s)}}this.metaObjectsByType={};for(let e in this.metaObjects){const t=this.metaObjects[e],i=t.type;t.children&&(t.children=null),(this.metaObjectsByType[i]||(this.metaObjectsByType[i]={}))[e]=t}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.parentId){const e=this.metaObjects[t.parentId];e&&(t.parent=e,(e.children||(e.children=[])).push(t))}}delete this.metaModels[e];for(let e in this.metaObjects){this.metaObjects[e].metaModels=[]}for(let e in this.metaModels){const t=this.metaModels[e];for(let e in t.metaObjects){t.metaObjects[e].metaModels.push(t)}}this.fire("metaModelDestroyed",e)}}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,i){const s=[],r=this.metaObjects[e],o=t&&t.length>0?tu(t):null,n=i&&i.length>0?tu(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r<l;r++)a(i[r])};return a(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function tu(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}
23
+ **/let Ul=null;function Ll(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const c=Math.min(r=Ul[i],o=Ul[i+1],n=Ul[i+2]),h=Math.min(a=Ul[s],l=Ul[s+1],A=Ul[s+2]);if(c!==h)return c-h;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let kl=null;function Ol(e,t){let i=kl[2*e]-kl[2*t];return 0!==i?i:kl[2*e+1]-kl[2*t+1]}function Nl(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e<t;e++)i[e]=e;Ul=new Int32Array(e.length);for(let i=0,s=e.length;i<s;i++)Ul[i]=e[i]>>t;i.sort(Ll);const s=new Int32Array(e.length);for(let t=0,r=i.length;t<r;t++)s[3*t+0]=e[3*i[t]+0],s[3*t+1]=e[3*i[t]+1],s[3*t+2]=e[3*i[t]+2];return s}(e.indices||[],t),o=function(e){if(0===(e||[]).length)return[];let t=new Int32Array(e.length/2);for(let e=0,i=t.length;e<i;e++)t[e]=e;for(let t=0,i=e.length;t<i;t+=2)if(e[t]>e[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}kl=new Int32Array(e),t.sort(Ol);const i=new Int32Array(e.length);for(let s=0,r=t.length;s<r;s++)i[2*s+0]=e[2*t[s]+0],i[2*s+1]=e[2*t[s]+1];return i}(e.edgeIndices||[]);function n(e,t){if(e>t){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<<t))return[e];const A=new Int32Array(l);A.fill(-1);const c=[];function h(){A.fill(-1);const e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}let u=h();for(let t=0,i=r.length;t<i;t+=3){let i=0;const l=r[t],c=r[t+1],d=r[t+2];if(-1===A[l]&&i++,-1===A[c]&&i++,-1===A[d]&&i++,i+u.numPositions>u.maxNumPositions&&(u=h()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[c]&&(A[c]=u.numPositions++,u.positionsCompressed.push(s[3*c]),u.positionsCompressed.push(s[3*c+1]),u.positionsCompressed.push(s[3*c+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[c]),u.indices.push(A[d]),(p=n(l,c))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(c,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let m=0,g=-s.length/3;return c.forEach((e=>{m+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,g+=e.positionsCompressed.length/3})),m>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e<s;e+=3){const s=n[3*t[e]]+"_"+n[3*t[e]+1]+"_"+n[3*t[e]+2]+"/"+n[3*t[e+1]]+"_"+n[3*t[e+1]+1]+"_"+n[3*t[e+1]+2]+"/"+n[3*t[e+2]]+"_"+n[3*t[e+2]+1]+"_"+n[3*t[e+2]+2];i[s]=!0}r+=e.edgeIndices.length/2;for(let e=0,t=o.length;e<t;e+=2){const t=n[3*o[e]]+"_"+n[3*o[e]+1]+"_"+n[3*o[e]+2]+"/"+n[3*o[e+1]]+"_"+n[3*o[e+1]+1]+"_"+n[3*o[e+1]+2]+"/";s[t]=!0}}));{const e=t.indices;t.edgeIndices;const s=t.positionsCompressed;for(let t=0,r=e.length;t<r;t+=3){const r=s[3*e[t]]+"_"+s[3*e[t]+1]+"_"+s[3*e[t]+2]+"/"+s[3*e[t+1]]+"_"+s[3*e[t+1]+1]+"_"+s[3*e[t+1]+2]+"/"+s[3*e[t+2]]+"_"+s[3*e[t+2]+1]+"_"+s[3*e[t+2]+2];if(!(r in i))throw console.log("Not found "+r),"Ohhhh!"}}}(c,e),c)}const Vl=new Float32Array([0,0,0]),Ql=new Uint16Array([0,0,0]);h.OBB3();class Hl{constructor(e,t,i,s,r,o){this._isObject=t,this.scene=e.scene,this.model=e,this.isSceneModelEntity=!0,this.meshes=s,this._numPrimitives=0,this._capMaterial=null;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=i,this.originalSystemId=h.unglobalizeObjectId(e.id,i),this._flags=r,this._aabb=h.AABB3(),this._aabbDirty=!0,this._offset=h.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!o,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(Gi)}set visible(e){if(!!(this._flags&Gi)!==e){this._flags=e?this._flags|Gi:this._flags&~Gi;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(Zi)}set highlighted(e){if(!!(this._flags&Zi)!==e){this._flags=e?this._flags|Zi:this._flags&~Zi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(Ki)}set xrayed(e){if(!!(this._flags&Ki)!==e){this._flags=e?this._flags|Ki:this._flags&~Ki;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(Ji)}set selected(e){if(!!(this._flags&Ji)!==e){this._flags=e?this._flags|Ji:this._flags&~Ji;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(Yi)}set edges(e){if(!!(this._flags&Yi)!==e){this._flags=e?this._flags|Yi:this._flags&~Yi;for(var t=0,i=this.meshes.length;t<i;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&ji)!==e){this._flags=e?this._flags|ji:this._flags&~ji;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(Wi)}set clippable(e){if(!!(this._flags&Wi)!==e){this._flags=e?this._flags|Wi:this._flags&~Wi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(Xi)}set collidable(e){if(!!(this._flags&Xi)!==e){this._flags=e?this._flags|Xi:this._flags&~Xi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(zi)}set pickable(e){if(!!(this._flags&zi)!==e){this._flags=e?this._flags|zi:this._flags&~zi;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return Vl[0]=e[0]/255,Vl[1]=e[1]/255,Vl[2]=e[2]/255,Vl}set colorize(e){if(e){Ql[0]=Math.floor(255*e[0]),Ql[1]=Math.floor(255*e[1]),Ql[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(Ql)}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,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(s,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}set capMaterial(e){this.scene.readableGeometryEnabled&&(this._capMaterial=e instanceof Xt?e:null,this.scene._capMaterialUpdated(this.id,this.model.id))}get capMaterial(){return this._capMaterial}getEachVertex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachVertex(e)}getEachIndex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachIndex(e)}getGeometryData(){let e=0;const t=[],i=[];for(let s=0,r=this.meshes.length;s<r;s++){const r=this.meshes[s];if(r.layer.readGeometryData){const s=r.layer.readGeometryData(r.portionId);for(let t=0,r=s.indices.length;t<r;t++)i.push(s.indices[t]+e);for(let e=0,i=s.positions.length;e<i;e++)t.push(s.positions[e]);e+=s.positions.length/3}}return{indices:i,positions:t}}get volume(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].volume;if(i<0)return-1;e+=i}return e}get surfaceArea(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].surfaceArea;i>=0&&(e+=i)}return e>0?e:-1}_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._deRegisterVisibleObject(this),this.xrayed&&e._deRegisterXRayedObject(this),this.selected&&e._deRegisterSelectedObject(this),this.highlighted&&e._deRegisterHighlightedObject(this),this._colorizeUpdated&&this.scene._deRegisterColorizedObject(this),this._opacityUpdated&&this.scene._deRegisterOpacityObject(this),!this._offset||0===this._offset[0]&&0===this._offset[1]&&0===this._offset[2]||this.scene._deRegisterOffsetObject(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const Gl=h.vec4(4),jl=h.vec4(),zl=h.vec4(),Wl=h.vec3([1,0,0]),Xl=h.vec3([0,1,0]),Kl=h.vec3([0,0,1]);h.vec3(3),h.vec3(3);const Zl=h.identityMat4();class Jl{constructor(e){this._model=e.model,this.id=e.id,this._parentTransform=e.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=h.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=h.identityMat4(new Float32Array(16)),this._worldMatrix=h.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,e.matrix?this.matrix=e.matrix:(this.scale=e.scale,this.position=e.position,e.quaternion||(this.rotation=e.rotation)),e.parent&&e.parent._addChildTransform(this)}_addChildTransform(e){this._childTransforms.push(e),e._parentTransform=this,e._transformDirty(),e._setSubtreeAABBsDirty(this)}_addMesh(e){this._meshes.push(e),e.transform=this}get parentTransform(){return this._parentTransform}get meshes(){return this._meshes}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.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._model.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._model.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=h.identityMat4()),this._localMatrix.set(e||Zl),h.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.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 Gl[0]=e[0],Gl[1]=e[1],Gl[2]=e[2],Gl[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Gl,jl),h.mulQuaternions(this.quaternion,jl,zl),this.quaternion=zl,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return Gl[0]=e[0],Gl[1]=e[1],Gl[2]=e[2],Gl[3]=t*h.DEGTORAD,h.angleAxisToQuaternion(Gl,jl),h.mulQuaternions(jl,this.quaternion,jl),this}rotateX(e){return this.rotate(Wl,e)}rotateY(e){return this.rotate(Xl,e)}rotateZ(e){return this.rotate(Kl,e)}translate(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateX(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateY(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateZ(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._transformDirty()}_transformDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._childTransforms.length;e<t;e++){const t=this._childTransforms[e];if(t._transformDirty(),t._meshes&&t._meshes.length>0){const e=t._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}if(this._meshes&&this._meshes.length>0){const e=this._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}_buildWorldMatrix(){const e=this.matrix;if(this._parentTransform)h.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._childTransforms)for(let t=0,i=e._childTransforms.length;t<i;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}const Yl=h.vec3(),ql=h.OBB3(),$l=h.vec4(),eA=h.vec3([1,1,1]),tA=h.vec3([0,0,0]);h.vec3([0,0,0]);const iA=h.identityQuaternion(),sA=h.identityMat4(),rA=new Uint8Array([255,255,255]);class oA extends T{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!1,this._vboBatchingLayerScratchMemory=(Hi++,Qi),this._textureTranscoder=t.textureTranscoder||Il(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=h.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboInstancingLayers={},this._vboBatchingLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._layersToFinalize=[],this._entityList=[],this._entitiesToFinalize=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._transforms={},this._meshes={},this._unusedMeshes={},this._entities={},this.renderFlags=new Rt,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._layersFinalized=!1,this._edgeThreshold=t.edgeThreshold||10,this._origin=h.vec3(t.origin||[0,0,0]),this._position=h.vec3(t.position||[0,0,0]),this._rotation=h.vec3(t.rotation||[0,0,0]),this._quaternion=h.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=h.vec4(t.quaternion||[0,0,0,1]),t.rotation&&h.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=h.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=h.mat4(),this._worldRotationMatrixConjugate=h.mat4(),this._matrix=h.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=h.mat4(),h.inverseMat4(this._matrix,this._worldNormalMatrix),h.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=h.mat4(),this._viewNormalMatrix=h.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),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.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new vl({id:"defaultColorTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new vl({id:"defaultMetalRoughTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new vl({id:"defaultNormalsTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new vl({id:"defaultEmissiveTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new vl({id:"defaultOcclusionTexture",texture:new ei({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new _l({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),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._setWorldMatrixDirty(),this._sceneModelDirty(),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._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||sA),h.decomposeMat4(this._matrix,this._position,this._quaternion,this._scale),h.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(h.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),h.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),h.quaternionToRotationMat4(this._conjugateQuaternion,this._worldRotationMatrixConjugate),h.scaleMat4v(this._scale,this._worldRotationMatrix),h.scaleMat4v(this._scale,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),h.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._viewMatrixDirty=!0)}get rotationMatrixConjugate(){return this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}get worldMatrix(){return this.matrix}get worldNormalMatrix(){return this._worldNormalMatrix}_rebuildViewMatrices(){this._rebuildMatrices(),this._viewMatrixDirty&&(h.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),h.inverseMat4(this._viewMatrix,this._viewNormalMatrix),h.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1)}get viewMatrix(){return this._viewMatrix?(this._rebuildViewMatrices(),this._viewMatrix):this.scene.camera.viewMatrix}get viewNormalMatrix(){return this._viewNormalMatrix?(this._rebuildViewMatrices(),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}get backfaces(){return this._backfaces}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get entityList(){return this._entityList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){if(this._aabbDirty){h.collapseAABB3(this._aabb);for(let e=0,t=this._entityList.length;e<t;e++)h.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}get visible(){return this.numVisibleLayerPortions>0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].visible=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].xrayed=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].highlighted=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].selected=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].edges=e;this.glRedraw()}get culled(){return this._culled}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].culled=e;this.glRedraw()}get clippable(){return this._clippable}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].clippable=e;this.glRedraw()}get collidable(){return this._collidable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].collidable=e}get pickable(){return this.numPickableLayerPortions>0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].pickable=e}get colorize(){return this._colorize}set colorize(e){this._colorize=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].colorize=e}get opacity(){return this._opacity}set opacity(e){this._opacity=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].opacity=e}get castsShadow(){return this._castsShadow}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get colorTextureEnabled(){return this._colorTextureEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}createQuantizationRange(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:zs(e.aabb,h.mat4())}:this.error("[createQuantizationRange] Config missing: id")}createGeometry(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`[createGeometry] Param expected: indices (required for '${e.primitive}' primitive type)`),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=zs(e.positionsDecodeBoundary,h.mat4())),e.positions){const t=h.collapseAABB3();e.positionsDecodeMatrix=h.mat4(),h.expandAABB3Points3(t,e.positions),e.positionsCompressed=js(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=h.collapseAABB3();e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed),h.expandAABB3Points3(t,e.positionsCompressed),he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}else if(e.buckets){const t=h.collapseAABB3();this._dtxBuckets[e.id]=e.buckets;for(let i=0,s=e.buckets.length;i<s;i++){const s=e.buckets[i];s.positions?h.expandAABB3Points3(t,s.positions):s.positionsCompressed&&h.expandAABB3Points3(t,s.positionsCompressed)}e.positionsDecodeMatrix&&he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e<s;e++)i[e]=255*t[e];e.colorsCompressed=i}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=re(e.positions,e.indices,null,5):e.edgeIndices=re(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){const t=he.getUVBounds(e.uv),i=he.compressUVs(e.uv,t.min,t.max);e.uvCompressed=i.quantized,e.uvDecodeMatrix=i.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error(`[createGeometry] Unsupported value for 'primitive': '${e.primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);else this.error("[createGeometry] Config missing: id")}createTexture(e){const t=e.id;if(null==t)return void this.error("[createTexture] Config missing: id");if(this._textures[t])return void this.error("[createTexture] Texture already created: "+t);if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;let i=e.minFilter||1008;1006!==i&&1007!==i&&1008!==i&&1005!==i&&1004!==i&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),i=1008);let s=e.magFilter||1006;1006!==s&&1003!==s&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),s=1006);let r=e.wrapS||1e3;1001!==r&&1002!==r&&1e3!==r&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),r=1e3);let o=e.wrapT||1e3;1001!==o&&1002!==o&&1e3!==o&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),o=1e3);let n=e.wrapR||1e3;1001!==n&&1002!==n&&1e3!==n&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),n=1e3);let a=e.encoding||3e3;3e3!==a&&3001!==a&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),a=3e3);const l=new ei({gl:this.scene.canvas.gl,minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,encoding:a});if(e.preloadColor&&l.setPreloadColor(e.preloadColor),e.image){const t=e.image;if(t.crossOrigin="Anonymous",t.compressed){const e=t.data;l.setCompressedData({mipmaps:e,props:{format:e[0].format,minFilter:i,magFilter:s}})}else l.setImage(t,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const A=new Image;A.onload=()=>{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new vl({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new _l({id:t,model:this,colorTexture:i,alphaCutoff:e.alphaCutoff,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new Jl({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?h.addVec3(this._origin,e.origin,h.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||eA,i=e.position||tA;e.rotation?(h.eulerToQuaternion(e.rotation,"XYZ",$l),e.meshMatrix=h.composeMat4(i,$l,t,h.mat4())):e.meshMatrix=h.composeMat4(i,e.quaternion||iA,t,h.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=zs(e.positionsDecodeBoundary,h.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):rA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=h.vec3(),i=[];je(e.positions,i,t)&&(e.positions=i,e.origin=h.addVec3(e.origin,t,t))}if(e.positions){const t=h.collapseAABB3();e.positionsDecodeMatrix=h.mat4(),h.expandAABB3Points3(t,e.positions),e.positionsCompressed=js(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=h.collapseAABB3();h.expandAABB3Points3(t,e.positionsCompressed),he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=h.collapseAABB3();for(let i=0,s=e.buckets.length;i<s;i++){const s=e.buckets[i];s.positions?h.expandAABB3Points3(t,s.positions):s.positionsCompressed&&h.expandAABB3Points3(t,s.positionsCompressed)}e.positionsDecodeMatrix&&he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}e.meshMatrix&&(h.AABB3ToOBB3(e.aabb,ql),h.transformOBB3(e.meshMatrix,ql),h.OBB3ToAABB3(ql,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=re(e.positions,e.indices,null,2):e.edgeIndices=re(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.buckets||(e.buckets=nA(e,this._enableVertexWelding&&this._enableIndexBucketing))}else{if(e.type=1,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.positions){const t=[];je(e.positions,t,Yl)&&(e.positions=t,e.origin=h.addVec3(e.origin,Yl,h.vec3()))}if(e.positions){const t=h.collapseAABB3();e.meshMatrix&&(h.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),h.expandAABB3Points3(t,e.positions),e.aabb=t}else{const t=h.collapseAABB3();h.expandAABB3Points3(t,e.positionsCompressed),he.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.meshMatrix&&(h.AABB3ToOBB3(e.aabb,ql),h.transformOBB3(e.meshMatrix,ql),h.OBB3ToAABB3(ql,e.aabb)),e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=re(e.positions,e.indices,null,2):e.edgeIndices=re(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId],!e.textureSet))return this.error(`[createMesh] Texture set not found: ${e.textureSetId} - ensure that you create it first with createTextureSet()`),!1}}else{if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)"),!1;if(e.geometry=this._geometries[e.geometryId],!e.geometry)return this.error(`[createMesh] Geometry not found: ${e.geometryId} - ensure that you create it first with createGeometry()`),!1;if(e.origin=e.origin?h.addVec3(this._origin,e.origin,h.vec3()):this._origin,e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.transformId){if(e.transform=this._transforms[e.transformId],!e.transform)return this.error(`[createMesh] Transform not found: ${e.transformId} - ensure that you create it first with createTransform()`),!1;e.aabb=e.geometry.aabb}else{if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||eA,i=e.position||tA;e.rotation?(h.eulerToQuaternion(e.rotation,"XYZ",$l),e.meshMatrix=h.composeMat4(i,$l,t,h.mat4())):e.meshMatrix=h.composeMat4(i,e.quaternion||iA,t,h.mat4())}h.AABB3ToOBB3(e.geometry.aabb,ql),h.transformOBB3(e.meshMatrix,ql),e.aabb=h.OBB3ToAABB3(ql,h.AABB3())}if(!(!this._dtxEnabled||"triangles"!==e.geometry.primitive&&"solid"!==e.geometry.primitive&&"surface"!==e.geometry.primitive||e.textureSetId)){e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):rA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255;let t=this._dtxBuckets[e.geometryId];t||(t=nA(e.geometry,this._enableVertexWelding,this._enableIndexBucketing),this._dtxBuckets[e.geometryId]=t),e.buckets=t}else e.type=0,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):rA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.metallic=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,e.roughness=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,e.textureSetId&&(e.textureSet=this._textureSets[e.textureSetId])}return e.numPrimitives=this._getNumPrimitives(e),this._createMesh(e)}_createDefaultIndices(e){const t=[];for(let i=0;i<e;i++)t.push(i);return t}_createMesh(e){const t=new Vi(this,e.id,e.color,e.opacity,e.transform,e.textureSet);t.pickId=this.scene._renderer.getPickID(t);const i=t.pickId,s=i>>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=h.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),t.numPrimitives=e.numPrimitives,this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:const i=e.geometry;t+=i.positions?i.positions.length:i.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}_getDTXLayer(e){const t=e.origin,i=e.geometry?e.geometry.primitive:e.primitive,s=`.${i}.${Math.round(t[0])}.${Math.round(t[1])}.${Math.round(t[2])}`;let r=this._dtxLayers[s];if(r){if(r.canCreatePortion(e))return r;delete this._dtxLayers[s],r=null}switch(i){case"triangles":case"solid":case"surface":r=new gl(this,{layerIndex:0,origin:t,primitive:i});break;case"lines":r=new Xn(this,{layerIndex:0,origin:t,primitive:i});break;default:return}return this._dtxLayers[s]=r,this.layerList.push(r),this._layersToFinalize.push(r),r}_getVBOBatchingLayer(e){const t=this,i=e.origin;e.renderLayer;const s=e.positionsDecodeMatrix||e.positionsDecodeBoundary?this._createHashStringFromMatrix(e.positionsDecodeMatrix||e.positionsDecodeBoundary):"-",r=e.textureSetId||"-",o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${e.primitive}.${s}.${r}`;let n=this._vboBatchingLayers[o];if(n)return n;let a=e.textureSet;for(;!n;){switch(e.primitive){case"triangles":case"solid":case"surface":n=new rr({model:t,textureSet:a,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===e.primitive,autoNormals:!0,primitive:e.primitive});break;case"lines":n=new fo({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive});break;case"points":n=new sn({model:t,layerIndex:0,scratchMemory:this._vboBatchingLayerScratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,uvDecodeMatrix:e.uvDecodeMatrix,origin:i,maxGeometryBatchSize:this._maxGeometryBatchSize,primitive:e.primitive})}const s=e.positionsCompressed?e.positionsCompressed.length:e.positions.length;("points"===e.primitive?n.canCreatePortion(s):n.canCreatePortion(s,e.indices.length))||(n.finalize(),delete this._vboBatchingLayers[o],n=null)}return this._vboBatchingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}_createHashStringFromMatrix(e){const t=e.join("");let i=0;for(let e=0;e<t.length;e++){i=(i<<5)-i+t.charCodeAt(e),i|=0}return(i>>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Zr({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Zr({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Uo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new Fn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),this._layersToFinalize.push(n),n}createEntity(e){if(void 0===e.id?e.id=h.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=h.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;return this._visible&&!1!==e.visible&&(t|=Gi),this._pickable&&!1!==e.pickable&&(t|=zi),this._culled&&!1!==e.culled&&(t|=ji),this._clippable&&!1!==e.clippable&&(t|=Wi),this._collidable&&!1!==e.collidable&&(t|=Xi),this._edges&&!1!==e.edges&&(t|=Yi),this._xrayed&&!1!==e.xrayed&&(t|=Ki),this._highlighted&&!1!==e.highlighted&&(t|=Zi),this._selected&&!1!==e.selected&&(t|=Ji),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;i<s;i++){const s=e.meshIds[i];let r=this._meshes[s];r?r.parent?this.error(`Mesh with ID "${s}" already belongs to object with ID "${r.parent.id}" - ignoring this mesh`):(t.push(r),delete this._unusedMeshes[s]):this.error(`Mesh with this ID not found: "${s}" - ignoring this mesh`)}const i=new Hl(this,e.isObject,e.id,t,e.flags,!0);return this._entityList.push(i),this._entities[e.id]=i,this._entitiesToFinalize.push(i),this.numEntities++,i}preFinalize(){if(this.destroyed)return!1;if(0===this._layersToFinalize.length)return!1;this._createDummyEntityForUnusedMeshes();for(let e=0,t=this._layersToFinalize.length;e<t;e++){this._layersToFinalize[e].finalize()}this._vboBatchingLayers={},this._vboInstancingLayers={},this._dtxLayers={},this._layersToFinalize=[];for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize()}for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize2()}this._entitiesToFinalize=[],this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position,this.layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].layerIndex=e}this.glRedraw(),this._layersFinalized=!0}finalize(){this.destroyed||(this.preFinalize(),this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={})}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t<i;t++){const i=this.layerList[t];this._getActiveSectionPlanesForLayer(i)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_createDummyEntityForUnusedMeshes(){const e=Object.keys(this._unusedMeshes);if(e.length>0){const t=`${this.id}-${h.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e<s;e++){i[e].active?(t.sectionPlanesActivePerLayer[r+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[r+e]=!1}return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t<s;t++){const s=i.visibleLayers[t];this.layerList[s].drawColorOpaque(i,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawShadow(t,e)}}setPickMatrices(e,t){if(0===this._numVisibleLayerPortions)return;const i=this.renderFlags;for(let s=0,r=i.visibleLayers.length;s<r;s++){const r=i.visibleLayers[s],o=this.layerList[r];o.setPickMatrices&&o.setPickMatrices(e,t)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this.layerList[s].drawPickNormals(t,e)}}drawSnapInit(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnapInit&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnapInit(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}drawSnap(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i],r=this.layerList[s];r.drawSnap&&(e.snapPickOrigin=[0,0,0],e.snapPickCoordinateScale=[1,1,1],e.snapPickLayerNumber++,r.drawSnap(t,e),e.snapPickLayerParams[e.snapPickLayerNumber]={origin:e.snapPickOrigin.slice(),coordinateScale:e.snapPickCoordinateScale.slice()})}}destroy(){for(let e in this._vboBatchingLayers)this._vboBatchingLayers.hasOwnProperty(e)&&this._vboBatchingLayers[e].destroy();this._vboBatchingLayers={};for(let e in this._vboInstancingLayers)this._vboInstancingLayers.hasOwnProperty(e)&&this._vboInstancingLayers[e].destroy();this._vboInstancingLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(let e=0,t=this.layerList.length;e<t;e++)this.layerList[e].destroy();this.layerList=[];for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._destroy();this._layersToFinalize={},this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==Hi&&(Hi--,0===Hi&&Qi._clear()),super.destroy()}}function nA(e,t,i){let s,r,o,n;if(t||i?[s,r,o]=Rl({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(s=e.positionsCompressed,r=e.indices,o=e.edgeIndices),i){n=Nl({positionsCompressed:s,indices:r,edgeIndices:o},s.length/3>65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class aA extends T{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],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._color=t.color||[1,1,1],this._opacity=t.opacity||1,this._sceneModel=new oA(this,{isModel:!1}),this._sceneModel.createMesh({id:"linesMesh",primitive:"lines",positions:this._positions,indices:this._indices,color:this._color,opacity:this._opacity}),this._sceneModel.createEntity({meshIds:["linesMesh"],visible:t.visible,clippable:t.clippable,collidable:t.collidable}),this._sceneModel.finalize(),this.scene._lineSetCreated(this)}set visible(e){this._sceneModel.visible=e}get visible(){return this._sceneModel.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}class lA extends T{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class AA extends lA{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 cA{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.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,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e<r.length;e++)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+e,s.TEXTURE_2D,r[e],0);if(e.length>0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},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,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),c=this.gl;return c.readBuffer(c.COLOR_ATTACHMENT0+n),c.readPixels(a,l,1,1,i||c.RGBA,s||c.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,c=new Uint8Array(4*n);for(let e=0;e<l;++e){const t=e*A,s=(a-e-1)*A;c.set(i.subarray(t,t+A)),i.copyWithin(t,s,s+A),i.set(c,s)}return r.data.set(i),o.putImageData(r,0,0),s}readImage(e){const t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,o=i.imageData,n=i.context,{width:a,height:l}=this.buffer;t.readPixels(0,0,a,l,t.RGBA,t.UNSIGNED_BYTE,s),o.data.set(s),n.putImageData(o,0,0),n.save(),n.globalCompositeOperation="copy",n.scale(1,-1),n.drawImage(r,0,-l,a,l),n.restore();let A=e.format||"png";return"jpeg"!==A&&"png"!==A&&"bmp"!==A&&(console.error("Unsupported image format: '"+A+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'png'"),A="png"),r.toDataURL(`image/${A}`)}_getImageDataCache(e=Uint8Array,t=4){const i=this.buffer.width,s=this.buffer.height;let r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){const o=document.createElement("canvas"),n=o.getContext("2d");o.width=i,o.height=s,r={pixelData:new e(i*s*t),canvas:o,context:n,imageData:n.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}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(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),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 hA extends lA{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 i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new ie({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,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];h.lookAtMat4v(s,i,r,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 cA(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()}}function uA(e){if(!dA(e.width)||!dA(e.height)){const t=document.createElement("canvas");t.width=pA(e.width),t.height=pA(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function dA(e){return 0==(e&e-1)}function pA(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class fA extends T{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new ie({texture:new ei({gl:i,target:i.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),p.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,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o<e.length;o++){const n=new Image;n.onload=function(){let e=n;const a=o;return function(){if(!s&&(e=uA(e),t._images[a]=e,r++,6===r)){let e=t._state.texture;e||(e=new ei({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),n.onerror=function(){s=!0},n.src=e[o]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),p.memory.textures--,this._state.destroy()}}const mA=h.vec4(),gA=h.vec4();class _A extends T{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){mA.set(this._viewPos),mA[3]=1,h.transformPoint4(this.scene.camera.projMatrix,mA,gA);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+gA[0]/gA[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-gA[1]/gA[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){this._entity!==e&&(this._cleanupDestroyedHandlers(),this._entity=e,this._entity&&(this._entity.isSceneModelEntity?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,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),Ge(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._cleanupDestroyedHandlers(),this._renderer.removeMarker(this),super.destroy()}_cleanupDestroyedHandlers(){this._entity&&(null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null))}}class vA{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,i=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:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const bA=h.vec3();const yA=h.vec3();class wA{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?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,c=!t||t.colorize,h=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),c){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}h&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,c=!t||t.opacity;var h=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[h]),s&&(t.edges=this.objectsEdges[h]),r&&(t.xrayed=this.objectsXrayed[h]),o&&(t.highlighted=this.objectsHighlighted[h]),n&&(t.selected=this.objectsSelected[h]),a&&(t.clippable=this.objectsClippable[h]),l&&(t.pickable=this.objectsPickable[h]),A&&(this.objectsHasColorize[h]?(yA[0]=this.objectsColorize[3*h+0],yA[1]=this.objectsColorize[3*h+1],yA[2]=this.objectsColorize[3*h+2],t.colorize=yA):t.colorize=null),c&&(t.opacity=this.objectsOpacity[h]),h++}}}const BA=h.vec3(),xA=h.vec3(),PA=h.vec4(),CA=h.vec3([0,0,-1]),MA=h.vec3([0,0,1]),FA=h.vec3([0,1,0]);class EA extends T{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new ie({active:!0,pos:h.vec3(),quaternion:h.vec4(),roll:0,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),this.scene.fire("sectionPlaneUpdated",this)}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 quaternion(e){this._state.quaternion.set(e||[0,0,0,-1]),h.vec3ApplyQuaternion(this._state.quaternion,MA,this._state.dir);const t=h.vec3ApplyQuaternion(this._state.quaternion,FA,BA),i=h.vec3PairToQuaternion(MA,this._state.dir,PA),s=h.vec3ApplyQuaternion(i,FA,xA),r=Math.acos(Math.min(1,h.dotVec3(t,s))),o=Math.sign(h.dotVec3(this._state.dir,h.cross3Vec3(t,s,xA)));this._state.roll=o*r,this._onDirUpdated()}get quaternion(){return this._state.quaternion}set roll(e){this._state.roll=e||0,this._onDirRollUpdated()}get roll(){return this._state.roll}set dir(e){this._state.dir.set(e||CA),this._onDirRollUpdated()}_onDirRollUpdated(){h.vec3PairToQuaternion(MA,this._state.dir,this._state.quaternion),PA[0]=0,PA[1]=0,PA[2]=-1,PA[3]=this._state.roll,h.angleAxisToQuaternion(PA,PA),h.mulQuaternions(this._state.quaternion,PA,this._state.quaternion),this._onDirUpdated()}_onDirUpdated(){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(){h.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}class IA{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}get snapped(){return this.snappedToEdge||this.snappedToVertex}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}}const TA={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isIphoneOrIpadSafari(){const e=window.navigator.userAgent,t=/iPhone|iPad/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isTouchDevice:()=>"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.mxMaxTouchPoints>0};class DA{constructor(e,t,i){this.id=i&&i.id?i.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)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}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)}}class SA extends T{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,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.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 i=this._element;i&&(i.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 RA=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class UA extends T{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 i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new SA(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],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<RA.length;e++)try{this.gl=this.canvas.getContext(RA[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="__",i=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,i.call(this,e))};let s={},r=e.bindTexture;e.bindTexture=function(e,i){s[t]!==i&&(s[t]=i,r.call(this,e,i))}}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,i,s){return this.scene._renderer.readPixels(e,t,i,s)}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 LA{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 i=this._rtcViewMats[e];return i||(i=this._getNewMat(),He(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}getRTCPickViewMatrix(e,t){let i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();const s=this.pickViewMatrix||this._scene.camera.viewMatrix;He(s,t,i),this._rtcPickViewMats[e]=i}return i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=h.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}class kA{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 i=this.markerList[t].rtcPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[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(new Float32Array(this.positions));this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new se(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new se(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3];let o=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const i=this.markerList[e];if(i.viewPos[2]>-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i];if(t.active){const e=h.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const s=0===e;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const OA=h.vec3([1,0,0]),NA=h.vec3();class VA{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 i=this._occlusionLayers[t];i||(i=new kA(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new kA(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.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,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester 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"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("out vec4 outColor;"),s.push("void main(void) {"),i){s.push(" float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push(" dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push(" if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new it(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,o=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,i=this._occlusionLayersList.length;e<i;e++){const i=this._occlusionLayersList[e];if(i.update(),i.culledBySectionPlanes)continue;const o=i.origin;t.uniformMatrix4fv(this._uViewMatrix,!1,He(r.viewMatrix,o));const n=s.sectionPlanes.length;if(n>0){const e=s.sectionPlanes;for(let s=0;s<n;s++){const r=this._uSectionPlanes[s];if(r){const n=i.sectionPlanesActive[s];if(t.uniform1i(r.active,n?1:0),n){const i=e[s];t.uniform3fv(r.pos,ze(i.dist,i.dir,o,NA)),t.uniform3fv(r.dir,i.dir)}}}}this._aPosition.bindArrayBuffer(i.positionsBuf);const a=i.indicesBuf;a.bind(),t.drawElements(t.POINTS,a.numItems,a.itemType,0)}}doOcclusionTest(){{const e=this._scene.canvas.resolutionScale,t=255*OA[0],i=255*OA[1],s=255*OA[2];for(let r=0,o=this._occlusionLayersList.length;r<o;r++){const o=this._occlusionLayersList[r];for(let r=0;r<o.lenOcclusionTestList;r++){const n=o.occlusionTestList[r],a=2*r,l=this._readPixelBuf.read(Math.round(o.pixels[a]*e),Math.round(o.pixels[a+1]*e)),A=l[0]===t&&l[1]===i&&l[2]===s;n._setVisible(A)}}}}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 QA=h.vec2();class HA{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,this.init()}init(){this._rebuild=!0}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(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,c=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;QA[0]=o,QA[1]=n,t.viewport(0,0,o,n),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),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,QA),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.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&&!this._rebuild)return;this._rebuild=!1;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new it(i,{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 s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new se(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new se(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new se(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.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 GA=new Float32Array(ZA(17,[0,1])),jA=new Float32Array(ZA(17,[1,0])),zA=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(KA(s,t));return i}(17,4)),WA=new Float32Array(2);class XA{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 it(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]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new se(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new se(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new se(e,e.ELEMENT_ARRAY_BUFFER,s,s.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,i){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(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,c=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),WA[0]=n,WA[1]=a,s.uniform2fv(this._uViewport,WA),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,c),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,jA):s.uniform2fv(this._uSampleOffsets,GA),s.uniform1fv(this._uSampleWeights,zA);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function KA(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function ZA(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class JA{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new cA(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}const YA=h.vec3([0,0,0]),qA=function(t,i){i=i||{};const s=new LA(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},c={},u=[],d=[],f=[],m=!0,g=!0,_=!0,v=!0,b=!0,y=!0,w=!0,B=!0;const x=new JA(t);let P=!1;const C=new HA(t),M=new XA(t);function F(){m&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),m=!1,g=!0),g&&(!function(){let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;t<s;t++){const s=i[t];u[e++]=s}}u.length=e,u.sort(((e,t)=>e.renderOrder-t.renderOrder))}(),g=!1,_=!0),_&&function(){let e=0,t=0;for(let i=0,s=u.length;i<s;i++){const s=u[i];s.rebuildRenderFlags(),s.renderFlags.culled||(s.isUI?f[t++]=s:d[e++]=s)}d.length=e,f.length=t}()}function E(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.shadowViewMatrix=e.getShadowViewMatrix(),s.shadowProjMatrix=e.getShadowProjMatrix(),o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,1),o.enable(o.DEPTH_TEST),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];!1!==i.visible&&i.castsShadow&&i.drawShadow&&(i.renderFlags.colorOpaque&&i.drawShadow(s))}}t.unbind()}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!Yt(o,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Yt(o,"WEBGL_compressed_texture_etc"),dxtSupported:!!Yt(o,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Yt(o,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Yt(o,"WEBGL_compressed_texture_pvrtc")&&!Yt(o,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){v=e,_=!0},this.setEdgesEnabled=function(e){b=e,_=!0},this.setSAOEnabled=function(e){y=e,_=!0},this.setPBREnabled=function(e){w=e,_=!0},this.setColorTextureEnabled=function(e){B=e,_=!0},this.needStateSort=function(){g=!0},this.shadowsDirty=function(){},this.imageDirty=function(){_=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){C.init(),M.init(),_=!0},this.addDrawable=function(e,t){const i=t.type;if(!i)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let s=A[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},A[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,m=!0},this.removeDrawable=function(e){const t=c[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const i=t.type,s=A[i];--s.count<=0?delete A[i]:delete s.drawableMap[e],delete c[e],m=!0},this.getPickID=function(e){return l.addItem(e)},this.putPickID=function(e){l.removeItem(e)},this.clear=function(e){if(o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT)},this.needsRender=function(){return _||m||g},this.render=function(e){(e=e||{}).force&&(_=!0),F(),_&&(!function(e){const i=t.sao;y&&i.possible&&function(e){const i=t.sao,r=x.getRenderBuffer("saoDepth",{depthTexture:!0});r.bind(),r.clear(),function(e){s.reset(),s.pass=e.pass,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=d.length;e<t;e++){const t=d[e];!0!==t.culled&&!1!==t.visible&&t.drawDepth&&t.saoEnabled&&(t.renderFlags.colorOpaque&&t.drawDepth(s))}}(e),r.unbind();const n=x.getRenderBuffer("saoOcclusion");if(n.bind(),n.clear(),C.render(r),n.unbind(),i.blur){const e=x.getRenderBuffer("saoOcclusion2");e.bind(),e.clear(),M.render(r,n,0),e.unbind(),n.bind(),n.clear(),M.render(r,e,1),n.unbind()}}(e);(function(){let e=t._lightsState.lights;for(let t=0,i=e.length;t<i;t++){const i=e[t];i.castsShadow&&E(i)}})(),function(e){const i=[],r=[],l=[],A=[],c=[],u=[],m=[],g=[],_=[],P=[],C=[],M=[],F=[],E=[],I=[],T=[],D=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=e.pass,s.withSAO=!1,s.pbrEnabled=w&&!!t.pbrEnabled,s.colorTextureEnabled=B&&!!t.colorTextureEnabled,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),n)o.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?D:t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),o.lineWidth(1),s.lineWidth=1;const S=t.sao.possible;if(y&&S){const e=x.getRenderBuffer("saoOcclusion");s.occlusionTexture=e?e.getTexture():null}else s.occlusionTexture=null;let R,U;const L=Date.now();!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const k=function(e){let d=0,p=0,f=0,w=0,B=0,x=0,D=0,L=0,k=0,O=0,N=0,V=0,Q=0,H=0,G=0,j=0;for(let t=0,o=e.length;t<o;t++){if(U=e[t],!0===U.culled||!1===U.visible)continue;const o=U.renderFlags;o.colorOpaque&&(y&&S&&U.saoEnabled?i[d++]=U:U.drawColorOpaque(s)),v&&o.colorTransparent&&(l[f++]=U),o.xrayedSilhouetteTransparent&&(m[D++]=U),o.xrayedSilhouetteOpaque&&(c[B++]=U),o.highlightedSilhouetteTransparent&&(C[N++]=U),o.highlightedSilhouetteOpaque&&(_[k++]=U),o.selectedSilhouetteTransparent&&(I[G++]=U),o.selectedSilhouetteOpaque&&(F[Q++]=U),U.edges&&b&&(o.edgesOpaque&&(r[p++]=U),o.edgesTransparent&&(A[w++]=U),o.selectedEdgesTransparent&&(T[j++]=U),o.selectedEdgesOpaque&&(E[H++]=U),o.xrayedEdgesTransparent&&(g[L++]=U),o.xrayedEdgesOpaque&&(u[x++]=U),o.highlightedEdgesTransparent&&(M[V++]=U),o.highlightedEdgesOpaque&&(P[O++]=U))}if(d>0)for(s.withSAO=!0,R=0;R<d;R++)i[R].drawColorOpaque(s);if(p>0)for(R=0;R<p;R++)r[R].drawEdgesColorOpaque(s);if(B>0)for(R=0;R<B;R++)c[R].drawSilhouetteXRayed(s);if(x>0)for(R=0;R<x;R++)u[R].drawEdgesXRayed(s);if(D>0||L>0||f>0||w>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(f>0||w>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),w>0)for(R=0;R<w;R++)U=A[R],U.drawEdgesColorTransparent(s);if(f>0){const e=s.pickOrigin||t.camera.eye,i=l.map((t=>({drawable:t,distSq:h.distVec3(t.origin||YA,e)})));for(i.sort(((e,t)=>t.distSq-e.distSq)),R=0;R<f;R++)i[R].drawable.drawColorTransparent(s)}if(L>0)for(R=0;R<L;R++)g[R].drawEdgesXRayed(s);if(D>0)for(R=0;R<D;R++)m[R].drawSilhouetteXRayed(s);o.disable(o.BLEND),a||o.depthMask(!0)}if(k>0||O>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),O>0)for(R=0;R<O;R++)P[R].drawEdgesHighlighted(s);if(k>0)for(R=0;R<k;R++)_[R].drawSilhouetteHighlighted(s)}if(N>0||V>0||k>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),V>0)for(R=0;R<V;R++)M[R].drawEdgesHighlighted(s);if(N>0)for(R=0;R<N;R++)C[R].drawSilhouetteHighlighted(s);o.disable(o.BLEND)}if(Q>0||H>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),H>0)for(R=0;R<H;R++)E[R].drawEdgesSelected(s);if(Q>0)for(R=0;R<Q;R++)F[R].drawSilhouetteSelected(s)}if(G>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),j>0)for(R=0;R<j;R++)T[R].drawEdgesSelected(s);if(G>0)for(R=0;R<G;R++)I[R].drawSilhouetteSelected(s);o.disable(o.BLEND)}};k(d),f.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),k(f));const O=Date.now(),N=p.frame;N.renderTime=(O-L)/1e3,N.drawElements=s.drawElements,N.drawArrays=s.drawArrays,N.useProgram=s.useProgram,N.bindTexture=s.bindTexture,N.bindArray=s.bindArray;const V=st.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<V;e++)o.activeTexture(o.TEXTURE0+e);o.bindTexture(o.TEXTURE_CUBE_MAP,null),o.bindTexture(o.TEXTURE_2D,null);const Q=st.MAX_VERTEX_ATTRIBS;for(let e=0;e<Q;e++)o.disableVertexAttribArray(e)}(e)}(e),p.frame.frameCount++,_=!1)},this.pick=function(){const e=h.vec3();h.mat4();const i=h.mat4(),n=h.vec3(),a=h.vec3([0,1,0]),c=new IA,u=h.vec2(),p=h.vec3(),m=h.vec3(),g=h.vec3();return h.vec3(),h.vec3(),function(_,v=c){let b;v.reset(),F();let y=null,w=null,B=null;v.pickSurface=_.pickSurface,_.canvasPos?(p[0]=_.canvasPos[0],p[1]=_.canvasPos[1],y=t.camera.viewMatrix,w=t.camera.projMatrix,B=t.camera.projection,u[0]=t.camera.project.near,u[1]=t.camera.project.far,v.canvasPos=_.canvasPos):(_.matrix?(y=_.matrix,w=t.camera.projMatrix,B=t.camera.projection,u[0]=t.camera.project.near,u[1]=t.camera.project.far):(m.set(_.origin||[0,0,0]),g.set(_.direction||[0,0,1]),b=h.addVec3(m,g,e),n[0]=Math.random(),n[1]=Math.random(),n[2]=Math.random(),h.normalizeVec3(n),h.cross3Vec3(g,n,a),y=h.lookAtMat4v(m,b,a,i),w=t.camera.ortho.matrix,B="ortho",u[0]=t.camera.ortho.near,u[1]=t.camera.ortho.far,v.origin=m,v.direction=g),p[0]=.5*r.clientWidth,p[1]=.5*r.clientHeight);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(y,w)}}const P=x.getRenderBuffer("pick",{size:[1,1]});P.bind();const C=function(e,i,r,n,a,A){const c=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=A.origin,s.pickViewMatrix=r,s.pickProjMatrix=n,s.pickInvisible=!!a.pickInvisible,s.pickClipPos=[D(i[0]*c,o.drawingBufferWidth),S(i[1]*c,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const h=a.includeEntityIds,u=a.excludeEntityIds,p=function(e){for(let t=0,i=e.length;t<i;t++){const i=e[t];!0!==i.culled&&!1!==i.visible&&(!i.drawPickMesh||!0!==a.pickInvisible&&!1===i.visible||!1===i.pickable||h&&!h[i.id]||u&&u[i.id]||i.drawPickMesh(s))}};p(d),f.length>0&&(o.clear(o.DEPTH_BUFFER_BIT),p(f));const m=e.read(0,0),g=m[0]+(m[1]<<8)+(m[2]<<16)+(m[3]<<24);if(g<0)return;return l.items[g]}(P,p,y,w,_,v);if(!C)return P.unbind(),null;const M=C.delegatePickedEntity?C.delegatePickedEntity():C;return M?(_.pickSurface&&(C.canPickTriangle&&C.canPickTriangle()?(!function(e,i,r,n,a,l){if(!i.drawPickTriangles)return;const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),i.drawPickTriangles(s);const c=e.read(0,0);let h=c[0]+256*c[1]+256*c[2]*256+256*c[3]*256*256;h*=3,l.primIndex=h}(P,C,p,y,w,v),C.pickTriangleSurface(y,w,B,v),v.pickSurfacePrecision=!1):C.canPickWorldPos&&C.canPickWorldPos()&&(I(P,C,p,y,w,u,v),!1!==_.pickSurfaceNormal&&function(e,i,r,n,a,l){const A=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=l.origin,s.pickViewMatrix=n,s.pickProjMatrix=a,s.pickClipPos=[D(r[0]*A,o.drawingBufferWidth),S(r[1]*A,o.drawingBufferHeight)];const c=x.getRenderBuffer("pick-normal",{size:[3,3]});c.bind(o.RGBA32I),o.viewport(0,0,c.size[0],c.size[1]),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),i.drawPickNormals(s);const u=c.read(1,1,o.RGBA_INTEGER,o.INT,Int32Array,4);c.unbind();const d=[u[0]/h.MAX_INT,u[1]/h.MAX_INT,u[2]/h.MAX_INT];h.normalizeVec3(d),l.worldNormal=d}(0,C,p,y,w,v),v.pickSurfacePrecision=!1)),P.unbind(),v.entity=M,v):(P.unbind(),null)}}();const I=function(){const e=h.vec4(),i=h.vec4(),n=h.vec4(),a=h.vec4(),l=h.vec4(),A=h.mat4(),c=h.mat4(),u=h.mat4();return function(d,p,f,m,g,_,v){const b=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickOrigin=v.origin,s.pickViewMatrix=m,s.pickProjMatrix=g,s.pickZNear=_[0],s.pickZFar=_[1],s.pickElementsCount=p.pickElementsCount,s.pickElementsOffset=p.pickElementsOffset,s.pickClipPos=[D(f[0]*b,o.drawingBufferWidth),S(f[1]*b,o.drawingBufferHeight)],o.viewport(0,0,1,1),o.clearColor(0,0,0,0),o.depthMask(!0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),p.drawPickDepths(s);const y=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256],i=[1/16777216,1/65536,1/256,1];return h.dotVec4(t,i)}(d.read(0,0)),w=(f[0]-r.clientWidth/2)/(r.clientWidth/2),B=-(f[1]-r.clientHeight/2)/(r.clientHeight/2),x=p.origin;let P;if(x){const e=He(m,x,A);P=h.mulMat4(g,e,c)}else P=h.mulMat4(g,m,c);const C=h.inverseMat4(P,u);e[0]=w,e[1]=B,e[2]=-1,e[3]=1;let M=h.transformVec4(C,e);M=h.mulVec4Scalar(M,1/M[3]),i[0]=w,i[1]=B,i[2]=1,i[3]=1;let F=h.transformVec4(C,i);F=h.mulVec4Scalar(F,1/F[3]);const E=h.subVec3(F,M,n),I=h.addVec3(M,h.mulVec4Scalar(E,y,a),l);x&&h.addVec3(I,x),v.worldPos=I}}();function T(e){e.snapPickLayerParams=e.snapPickLayerParams||[],e.snapPickLayerNumber=e.snapPickLayerParams.length;for(let t=0,i=d.length;t<i;t++){const i=d[t];i.drawSnapInit&&i.drawSnap&&!i.culled&&i.visible&&i.pickable&&i.drawSnap(e)}return e.snapPickLayerParams}function D(e,t){return e/t*2-1}function S(e,t){return 1-e/t*2}this.snapPick=function(){const e=new IA;return function(i,r=e){const{canvasPos:n,origin:a,direction:c,snapRadius:u,snapToVertex:p,snapToEdge:f}=i;if(!p&&!f)return this.pick({canvasPos:n,pickSurface:!0});const m=t.canvas.resolutionScale;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickZNear=t.camera.project.near,s.pickZFar=t.camera.project.far;const g=u||30,_=x.getRenderBuffer(`uniquePickColors-aabs-${g}`,{depthTexture:!0,size:[2*g+1,2*g+1]});s.snapVectorA=[n?D(n[0]*m,o.drawingBufferWidth):0,n?S(n[1]*m,o.drawingBufferHeight):0],s.snapInvVectorAB=[o.drawingBufferWidth/(2*g),o.drawingBufferHeight/(2*g)],_.bind(o.RGBA32I,o.RGBA32I,o.RGBA8UI),o.viewport(0,0,_.size[0],_.size[1]),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.disable(o.CULL_FACE),o.depthMask(!0),o.disable(o.BLEND),o.depthFunc(o.LEQUAL),o.clear(o.DEPTH_BUFFER_BIT),o.clearBufferiv(o.COLOR,0,new Int32Array([0,0,0,0])),o.clearBufferiv(o.COLOR,1,new Int32Array([0,0,0,0])),o.clearBufferuiv(o.COLOR,2,new Uint32Array([0,0,0,0])),s.pickViewMatrix=n?t.camera.viewMatrix:h.lookAtMat4v(a,h.addVec3(a,c,h.vec3()),h.vec3([0,1,0]),h.mat4());const v=t.camera.projMatrix;for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.setPickMatrices&&i.setPickMatrices(s.pickViewMatrix,v)}}o.drawBuffers([o.COLOR_ATTACHMENT0,o.COLOR_ATTACHMENT1,o.COLOR_ATTACHMENT2]);const b=function(e){e.snapPickLayerParams=[],e.snapPickLayerNumber=0;for(let t=0,i=d.length;t<i;t++){const i=d[t];i.drawSnapInit&&!i.culled&&i.visible&&i.pickable&&i.drawSnapInit(e)}return e.snapPickLayerParams}(s),y=[];s.snapPickLayerParams=y,o.depthMask(!1),o.drawBuffers([o.COLOR_ATTACHMENT0]),p&&f?(s.snapMode="edge",T(s),s.snapMode="vertex",s.snapPickLayerNumber++,T(s)):(s.snapMode=p?"vertex":"edge",T(s)),o.depthMask(!0);const w=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4),B=_.readArray(o.RGBA_INTEGER,o.INT,Int32Array,4,1),P=_.readArray(o.RGBA_INTEGER,o.UNSIGNED_INT,Uint32Array,4,2);_.unbind();let C=null,M=null,F=null;const E=4*g+g*_.size[0]*4,I=w.slice(E,E+4),R=B.slice(E,E+4),U=P.slice(E,E+4);if(0!==I[3]){const e=b[Math.abs(I[3])%b.length],t=e.origin,i=e.coordinateScale;C=[I[0]*i[0]+t[0],I[1]*i[1]+t[1],I[2]*i[2]+t[2]],M=h.normalizeVec3([R[0]/h.MAX_INT,R[1]/h.MAX_INT,R[2]/h.MAX_INT]);const s=U[0]+(U[1]<<8)+(U[2]<<16)+(U[3]<<24);F=l.items[s]}let L=[];for(let e=0;e<w.length;e+=4)if(w[e+3]>0){const t=Math.floor(e/4),i=_.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));L.push({x:s,y:r,dist:o,isVertex:p&&f?w[e+3]>y.length/2:p,result:[w[e+0],w[e+1],w[e+2],w[e+3]],normal:[B[e+0],B[e+1],B[e+2],B[e+3]],id:[P[e+0],P[e+1],P[e+2],P[e+3]]})}let k=null,O=null,N=null,V=null;if(L.length>0){L.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),V=L[0].isVertex?"vertex":"edge";const e=L[0].result,t=L[0].normal,i=L[0].id,s=y[e[3]],r=s.origin,o=s.coordinateScale;O=h.normalizeVec3([t[0]/h.MAX_INT,t[1]/h.MAX_INT,t[2]/h.MAX_INT]),k=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],N=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===C&&null==k)return null;let Q=null;null!==k&&(Q=t.camera.projectWorldPos(k));const H=N&&N.delegatePickedEntity?N.delegatePickedEntity():N;return!H&&F&&(F=F.delegatePickedEntity?F.delegatePickedEntity():F),r.reset(),r.snappedToEdge="edge"===V,r.snappedToVertex="vertex"===V,r.worldPos=k||C,r.worldNormal=O||M,r.entity=H||F,r.canvasPos=n||t.camera.projectWorldPos(C||k),r.snappedCanvasPos=Q||n,r}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new VA(t,x),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){F(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e=0,t=d.length;e<t;e++){const t=d[e];t.drawOcclusion&&!0!==t.culled&&!1!==t.visible&&!1!==t.pickable&&t.drawOcclusion(s)}this._occlusionTester.drawMarkers(s),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,s){const r=x.getRenderBuffer("snapshot");let o,n,a,l;for(r.bind(),r.clear(),this.render({force:!0,opaqueOnly:s}),n=0;n<i;n++)a=2*n,l=4*n,o=r.read(e[a],e[a+1]),t[l]=o[0],t[l+1]=o[1],t[l+2]=o[2],t[l+3]=o[3];r.unbind(),_=!0},this.beginSnapshot=function(e={}){const t=x.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),P=!0},this.renderSnapshot=function(){if(!P)return;x.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),_=!0},this.readSnapshot=function(e){return x.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return x.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){if(!P)return;x.getRenderBuffer("snapshot").unbind(),P=!1},this.destroy=function(){A={},c={},x.destroy(),C.destroy(),M.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class $A extends T{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.MOUSE_LEFT_BUTTON=260,this.MOUSE_MIDDLE_BUTTON=261,this.MOUSE_RIGHT_BUTTON=262,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())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!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("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){const t=e.target.getBoundingClientRect();this.mouseCanvasPos[0]=e.clientX-t.left,this.mouseCanvasPos[1]=e.clientY-t.top}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()}}class ec extends T{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new ie({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],i=e[3];this._state.boundary=[0,0,t,i],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 tc extends T{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),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],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),h.perspectiveMat4(s*(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:1e4;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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ic extends T{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({matrix:h.mat4(),inverseMatrix:h.mat4(),transposedMatrix:h.mat4(),near:.1,far:1e4}),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,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),h.orthoMat4c(n,a,A,l,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:1e4;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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class sc extends T{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class rc extends T{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new ie({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,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,h.mulMat4v4(this.inverseMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,h.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const oc=h.vec3(),nc=h.vec3(),ac=h.vec3(),lc=h.vec3(),Ac=h.vec3(),cc=h.vec3(),hc=h.vec4(),uc=h.vec4(),dc=h.vec4(),pc=h.mat4(),fc=h.mat4(),mc=h.vec3(),gc=h.vec3(),_c=h.vec3(),vc=h.vec3();class bc extends T{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new ie({offsetEyeFromLook:!0,deviceMatrix:h.mat4(),hasDeviceMatrix:!1,matrix:h.mat4(),normalMatrix:h.mat4(),inverseMatrix:h.mat4()}),this._perspective=new tc(this),this._ortho=new ic(this),this._frustum=new sc(this),this._customProjection=new rc(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&&this._state.offsetEyeFromLook?(h.subVec3(this._eye,this._look,mc),h.normalizeVec3(mc,gc),h.mulVec3Scalar(gc,1e3,_c),h.addVec3(this._look,_c,vc),t=vc):t=this._eye,e.hasDeviceMatrix?(h.lookAtMat4v(t,this._look,this._up,fc),h.mulMat4(e.deviceMatrix,fc,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,oc);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pc),t=h.transformPoint3(pc,t,nc),this.eye=h.addVec3(this._look,t,ac),this.up=h.transformPoint3(pc,this._up,lc)}orbitPitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._eye,this._look,oc);const i=h.cross3Vec3(h.normalizeVec3(t,nc),h.normalizeVec3(this._up,ac));h.rotationMat4v(.0174532925*e,i,pc),t=h.transformPoint3(pc,t,lc),this.up=h.transformPoint3(pc,this._up,Ac),this.eye=h.addVec3(t,this._look,cc)}yaw(e){let t=h.subVec3(this._look,this._eye,oc);h.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,pc),t=h.transformPoint3(pc,t,nc),this.look=h.addVec3(t,this._eye,ac),this._gimbalLock&&(this.up=h.transformPoint3(pc,this._up,lc))}pitch(e){if(this._constrainPitch&&(e=h.dotVec3(this._up,this._worldUp)/h.DEGTORAD)<1)return;let t=h.subVec3(this._look,this._eye,oc);const i=h.cross3Vec3(h.normalizeVec3(t,nc),h.normalizeVec3(this._up,ac));h.rotationMat4v(.0174532925*e,i,pc),this.up=h.transformPoint3(pc,this._up,cc),t=h.transformPoint3(pc,t,lc),this.look=h.addVec3(t,this._eye,Ac)}pan(e){const t=h.subVec3(this._eye,this._look,oc),i=[0,0,0];let s;if(0!==e[0]){const r=h.cross3Vec3(h.normalizeVec3(t,[]),h.normalizeVec3(this._up,nc));s=h.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=h.mulVec3Scalar(h.normalizeVec3(this._up,ac),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=h.mulVec3Scalar(h.normalizeVec3(t,lc),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=h.addVec3(this._eye,i,Ac),this.look=h.addVec3(this._look,i,cc)}zoom(e){const t=h.subVec3(this._eye,this._look,oc),i=Math.abs(h.lenVec3(t,nc)),s=Math.abs(i+e);if(s<.5)return;const r=h.normalizeVec3(t,ac);this.eye=h.addVec3(this._look,h.mulVec3Scalar(r,s),lc)}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,oc))}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}get offsetEyeFromLook(){return this._state.offsetEyeFromLook}set offsetEyeFromLook(e){this._state.offsetEyeFromLook=e,this._needUpdate(0)}projectWorldPos(e){const t=hc,i=uc,s=dc;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,h.mulMat4v4(this.viewMatrix,t,i),h.mulMat4v4(this.projMatrix,i,s),h.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}const yc={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 wc extends T{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 yc}set units(e){e||(e="meters");yc[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 Bc extends T{constructor(e,t={}){super(e,t),this._supported=st.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()}}class xc extends T{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const Pc={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class Cc extends Xt{get type(){return"PointsMaterial"}get presets(){return Pc}constructor(e,t={}){super(e,t),this._state=new ie({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=Pc[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(Pc).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 Mc={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class Fc extends Xt{get type(){return"LinesMaterial"}get presets(){return Mc}constructor(e,t={}){super(e,t),this._state=new ie({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=Mc[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Mc).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ec(e,t,i=2){const s=t&&t.length,r=s?t[0]*i:e.length;let o=Ic(e,0,r,i,!0);const n=[];if(!o||o.next===o.prev)return n;let a,l,A;if(s&&(o=function(e,t,i,s){const r=[];for(let i=0,o=t.length;i<o;i++){const n=Ic(e,t[i]*s,i<o-1?t[i+1]*s:e.length,s,!1);n===n.next&&(n.steiner=!0),r.push(Qc(n))}r.sort(kc);for(let e=0;e<r.length;e++)i=Oc(r[e],i);return i}(e,t,o,i)),e.length>80*i){a=1/0,l=1/0;let t=-1/0,s=-1/0;for(let o=i;o<r;o+=i){const i=e[o],r=e[o+1];i<a&&(a=i),r<l&&(l=r),i>t&&(t=i),r>s&&(s=r)}A=Math.max(t-a,s-l),A=0!==A?32767/A:0}return Dc(o,n,i,a,l,A,0),n}function Ic(e,t,i,s,r){let o;if(r===function(e,t,i,s){let r=0;for(let o=t,n=i-s;o<i;o+=s)r+=(e[n]-e[o])*(e[o+1]+e[n+1]),n=o;return r}(e,t,i,s)>0)for(let r=t;r<i;r+=s)o=qc(r/s|0,e[r],e[r+1],o);else for(let r=i-s;r>=t;r-=s)o=qc(r/s|0,e[r],e[r+1],o);return o&&Wc(o,o.next)&&($c(o),o=o.next),o}function Tc(e,t){if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!Wc(s,s.next)&&0!==zc(s.prev,s,s.next))s=s.next;else{if($c(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t}function Dc(e,t,i,s,r,o,n){if(!e)return;!n&&o&&function(e,t,i,s){let r=e;do{0===r.z&&(r.z=Vc(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,i=1;do{let s,r=e;e=null;let o=null;for(t=0;r;){t++;let n=r,a=0;for(let e=0;e<i&&(a++,n=n.nextZ,n);e++);let l=i;for(;a>0||l>0&&n;)0!==a&&(0===l||!n||r.z<=n.z)?(s=r,r=r.nextZ,a--):(s=n,n=n.nextZ,l--),o?o.nextZ=s:e=s,s.prevZ=o,o=s;r=n}o.nextZ=null,i*=2}while(t>1)}(r)}(e,s,r,o);let a=e;for(;e.prev!==e.next;){const l=e.prev,A=e.next;if(o?Rc(e,s,r,o):Sc(e))t.push(l.i,e.i,A.i),$c(e),e=A.next,a=A.next;else if((e=A)===a){n?1===n?Dc(e=Uc(Tc(e),t),t,i,s,r,o,2):2===n&&Lc(e,t,i,s,r,o):Dc(Tc(e),t,i,s,r,o,1);break}}}function Sc(e){const t=e.prev,i=e,s=e.next;if(zc(t,i,s)>=0)return!1;const r=t.x,o=i.x,n=s.x,a=t.y,l=i.y,A=s.y,c=Math.min(r,o,n),h=Math.min(a,l,A),u=Math.max(r,o,n),d=Math.max(a,l,A);let p=s.next;for(;p!==t;){if(p.x>=c&&p.x<=u&&p.y>=h&&p.y<=d&&Gc(r,a,o,l,n,A,p.x,p.y)&&zc(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function Rc(e,t,i,s){const r=e.prev,o=e,n=e.next;if(zc(r,o,n)>=0)return!1;const a=r.x,l=o.x,A=n.x,c=r.y,h=o.y,u=n.y,d=Math.min(a,l,A),p=Math.min(c,h,u),f=Math.max(a,l,A),m=Math.max(c,h,u),g=Vc(d,p,t,i,s),_=Vc(f,m,t,i,s);let v=e.prevZ,b=e.nextZ;for(;v&&v.z>=g&&b&&b.z<=_;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&Gc(a,c,l,h,A,u,v.x,v.y)&&zc(v.prev,v,v.next)>=0)return!1;if(v=v.prevZ,b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&Gc(a,c,l,h,A,u,b.x,b.y)&&zc(b.prev,b,b.next)>=0)return!1;b=b.nextZ}for(;v&&v.z>=g;){if(v.x>=d&&v.x<=f&&v.y>=p&&v.y<=m&&v!==r&&v!==n&&Gc(a,c,l,h,A,u,v.x,v.y)&&zc(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=_;){if(b.x>=d&&b.x<=f&&b.y>=p&&b.y<=m&&b!==r&&b!==n&&Gc(a,c,l,h,A,u,b.x,b.y)&&zc(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Uc(e,t){let i=e;do{const s=i.prev,r=i.next.next;!Wc(s,r)&&Xc(s,i,i.next,r)&&Jc(s,r)&&Jc(r,s)&&(t.push(s.i,i.i,r.i),$c(i),$c(i.next),i=e=r),i=i.next}while(i!==e);return Tc(i)}function Lc(e,t,i,s,r,o){let n=e;do{let e=n.next.next;for(;e!==n.prev;){if(n.i!==e.i&&jc(n,e)){let a=Yc(n,e);return n=Tc(n,n.next),a=Tc(a,a.next),Dc(n,t,i,s,r,o,0),void Dc(a,t,i,s,r,o,0)}e=e.next}n=n.next}while(n!==e)}function kc(e,t){let i=e.x-t.x;if(0===i&&(i=e.y-t.y,0===i)){i=(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)}return i}function Oc(e,t){const i=function(e,t){let i=t;const s=e.x,r=e.y;let o,n=-1/0;if(Wc(e,i))return i;do{if(Wc(e,i.next))return i.next;if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const e=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>n&&(n=e,o=i.x<i.next.x?i:i.next,e===s))return o}i=i.next}while(i!==t);if(!o)return null;const a=o,l=o.x,A=o.y;let c=1/0;i=o;do{if(s>=i.x&&i.x>=l&&s!==i.x&&Hc(r<A?s:n,r,l,A,r<A?n:s,r,i.x,i.y)){const t=Math.abs(r-i.y)/(s-i.x);Jc(i,e)&&(t<c||t===c&&(i.x>o.x||i.x===o.x&&Nc(o,i)))&&(o=i,c=t)}i=i.next}while(i!==a);return o}(e,t);if(!i)return t;const s=Yc(i,e);return Tc(s,s.next),Tc(i,i.next)}function Nc(e,t){return zc(e.prev,e,t.prev)<0&&zc(t.next,e,e.next)<0}function Vc(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-s)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Qc(e){let t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function Hc(e,t,i,s,r,o,n,a){return(r-n)*(t-a)>=(e-n)*(o-a)&&(e-n)*(s-a)>=(i-n)*(t-a)&&(i-n)*(o-a)>=(r-n)*(s-a)}function Gc(e,t,i,s,r,o,n,a){return!(e===n&&t===a)&&Hc(e,t,i,s,r,o,n,a)}function jc(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Xc(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Jc(e,t)&&Jc(t,e)&&function(e,t){let i=e,s=!1;const r=(e.x+t.x)/2,o=(e.y+t.y)/2;do{i.y>o!=i.next.y>o&&i.next.y!==i.y&&r<(i.next.x-i.x)*(o-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(zc(e.prev,e,t.prev)||zc(e,t.prev,t))||Wc(e,t)&&zc(e.prev,e,e.next)>0&&zc(t.prev,t,t.next)>0)}function zc(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Wc(e,t){return e.x===t.x&&e.y===t.y}function Xc(e,t,i,s){const r=Zc(zc(e,t,i)),o=Zc(zc(e,t,s)),n=Zc(zc(i,s,e)),a=Zc(zc(i,s,t));return r!==o&&n!==a||(!(0!==r||!Kc(e,i,t))||(!(0!==o||!Kc(e,s,t))||(!(0!==n||!Kc(i,e,s))||!(0!==a||!Kc(i,t,s)))))}function Kc(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Zc(e){return e>0?1:e<0?-1:0}function Jc(e,t){return zc(e.prev,e,e.next)<0?zc(e,t,e.next)>=0&&zc(e,e.prev,t)>=0:zc(e,t,e.prev)<0||zc(e,e.next,t)<0}function Yc(e,t){const i=eh(e.i,e.x,e.y),s=eh(t.i,t.x,t.y),r=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,o.next=s,s.prev=o,s}function qc(e,t,i,s){const r=eh(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function $c(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function eh(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const th=[0,1,0],ih=[1,0,0],sh=h.vec3(),rh=h.vec3(),oh=h.vec3(),nh=h.vec3(),ah=h.vec3();function lh(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6&&Math.abs(e[2]-t[2])<1e-6}class Ah{constructor(e){this.scene=e,this._resourcesAllocated=!1}_onCapMaterialUpdated(e,t){if(!this._resourcesAllocated){this._resourcesAllocated=!0,this._sectionPlanes=[],this._sceneModelsData={},this._dirtyMap={},this._prevIntersectionModelsMap={},this._sectionPlaneTimeout=null,this._updateTimeout=null;const e=e=>{const t=()=>{this._setAllDirty(!0),this._update()};this._sectionPlanes.push(e),e.on("pos",t),e.on("dir",t),e.on("active",t),e.once("destroyed",(()=>{const t=e.id;t&&(this._sectionPlanes=this._sectionPlanes.filter((e=>e.id!==t)),this._update())}).bind(this))};for(const t in this.scene.sectionPlanes)e(this.scene.sectionPlanes[t]);this._onSectionPlaneCreated=this.scene.on("sectionPlaneCreated",e),this._onTick=this.scene.on("tick",(()=>{let e=!1;for(const t in this._sceneModelsData)this.scene.models[t]?this._sceneModelsData[t].visible!==!!this.scene.models[t].visible&&(this._sceneModelsData[t].visible=!!this.scene.models[t].visible,e=!0):(delete this._sceneModelsData[t],e=!0);e&&this._update()}))}this._dirtyMap[t]||(this._dirtyMap[t]=new Map),this._dirtyMap[t].set(e,!0),this._update()}_update(){clearTimeout(this._updateTimeout),this._deletePreviousModels(),this._updateTimeout=setTimeout((()=>{clearTimeout(this._updateTimeout);const e=Object.values(this.scene.models).filter((e=>e.visible));this._addHatches(e,this._sectionPlanes.filter((e=>e.active))),this._setAllDirty(!1)}),100)}_setAllDirty(e){for(const t in this._dirty)this._dirtyMap[t].forEach(((i,s)=>this._dirtyMap[t].set(s,e)))}_addHatches(e,t){t.forEach((t=>{e.forEach((e=>{if(!this._doesPlaneIntersectBoundingBox(e.aabb,t))return;if(!this._dirtyMap[e.id])return;const i=new Map,s=e.objects,r=[h.vec3(),h.vec3(),h.vec3()];this._dirtyMap[e.id].forEach(((o,n)=>{if(!o)return;const a=s[n];if(!this._doesPlaneIntersectBoundingBox(a.aabb,t))return;if(!this._sceneModelsData[e.id]){const t=e.aabb;this._sceneModelsData[e.id]={verticesMap:new Map,indicesMap:new Map,modelOrigin:h.vec3([(t[0]+t[3])/2,(t[1]+t[4])/2,(t[2]+t[5])/2])}}const l=this._sceneModelsData[e.id],A=l.modelOrigin;if(!l.verticesMap.has(n)){const e=a.meshes[0].isSolid(),t=[],i=[];e&&a.capMaterial&&(a.getEachVertex((e=>t.push(e[0]-A[0],e[1]-A[1],e[2]-A[2]))),a.getEachIndex((e=>i.push(e)))),l.verticesMap.set(n,t),l.indicesMap.set(n,i)}const c=l.verticesMap.get(n),u=l.indicesMap.get(n),d=-h.dotVec3(h.subVec3(t.pos,A,sh),t.dir),p=[],f=u.length;for(let e=0;e<f;e+=3){for(let t=0;t<3;t++){const i=3*u[e+t];r[t][0]=c[i],r[t][1]=c[i+1],r[t][2]=c[i+2]}if(!r[0][0]&&!r[0][1]&&!r[0][2])continue;const i=[];for(let e=0;e<3;e++){const s=r[e],o=r[(e+1)%3],n=d+h.dotVec3(t.dir,s),a=d+h.dotVec3(t.dir,o);if(n*a>0)continue;const l=-n/(a-n);i.push(h.lerpVec3(l,0,1,s,o,h.vec3()))}2===i.length&&p.push(i)}p.length>0&&i.set(n,p)}));const o=new Map;i.forEach(((e,t)=>{o.set(t,[[e[0]]]),e.splice(0,1);let s=0;for(;e.length>0;){const r=o.get(t)[s][o.get(t)[s].length-1][1];let n=!1;for(let i=0;i<e.length;i++){const[a,l]=e[i];if(lh(r,a)){o.get(t)[s].push(e[i]),e.splice(i,1),n=!0;break}if(lh(r,l)){o.get(t)[s].push([l,a]),e.splice(i,1),n=!0;break}}if(!n&&lh(r,o.get(t)[s][0][0])&&e.length>1)o.get(t).push([i.get(t)[0]]),e.splice(0,1),s++;else if(!n)break}}));const n=new Map;o.forEach(((e,i)=>{const s=[];for(let i=0;i<e.length;i++)s.push([]),e[i].forEach((e=>{s[i].push([this._projectTo2D(e[0],t.dir),this._projectTo2D(e[1],t.dir)])}));n.set(i,s)}));const a=new Map;let l;n.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin;l=[];const o=i,n=[],A=new Set;for(let e=0;e<o.length;e++){if(A.has(e))continue;const t=[o[e]];A.add(e);for(let i=e+1;i<o.length;i++)A.has(i)||(this._isLoopInside(o[e],o[i])||this._isLoopInside(o[i],o[e]))&&(t.push(o[i]),A.add(i));n.push(t)}n.forEach((e=>{const i=[],s=[];let o=0;const n=e.map((e=>{let t=0;for(let i=0;i<e.length;i++){const s=(i+1)%e.length;t+=e[i][0][0]*e[s][0][1],t-=e[s][0][0]*e[i][0][1]}return Math.abs(t)/2})),a=n.indexOf(Math.max(...n));e[a].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2}));for(let t=0;t<e.length;t++)t!==a&&(s.push(o/2),e[t].forEach((e=>{i.push(e[0][0],e[0][1]),o+=2})));const A=Ec(i,s),c=[];for(let e=0;e<A.length;e+=3){const s=[];for(let o=0;o<3;o++){const n=2*A[e+o],a=[i[n],i[n+1]],l=this._convertTo3D(a,t,r);s.push(l)}c.push(s)}l.push(c)})),a.set(s,l)}));const A=new Map;a.forEach(((e,t)=>{l=[],e.forEach((e=>{const t=new Map,i=[],s=[];let r=0;e.forEach((e=>{const o=[];e.forEach((e=>{const s=`${e[0].toFixed(6)},${e[1].toFixed(6)},${e[2].toFixed(6)}`;t.has(s)?o.push(t.get(s)):(i.push(e[0],e[1],e[2]),t.set(s,r),o.push(r),r++)})),s.push(...o)})),l.push({positions:i,indices:s})})),A.set(t,l)})),this._prevIntersectionModelsMap[e.id]||(this._prevIntersectionModelsMap[e.id]=new Map),h.mulVec3Scalar(t.dir,.001,ah),A.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin,o=new Array(i.size);let n=0;i.forEach(((i,a)=>{const l=i.positions,A=i.indices;l.length;const c=h.buildNormals(l,A),u=this._createUVs(l,t,r);o[n++]=new zt(this.scene,{id:`${t.id}-${s}-${a}`,geometry:new pe(this.scene,{primitive:"triangles",positions:l,indices:A,normals:c,uv:u}),origin:h.addVec3(r,ah,sh),position:[0,0,0],rotation:[0,0,0],material:e.objects[s].capMaterial})})),this._prevIntersectionModelsMap[e.id].has(s)?this._prevIntersectionModelsMap[e.id].get(s).push(...o):this._prevIntersectionModelsMap[e.id].set(s,o)}))}))}))}_doesPlaneIntersectBoundingBox(e,t){const i=[e[0],e[1],e[2]],s=[e[3],e[4],e[5]],r=[[i[0],i[1],i[2]],[s[0],i[1],i[2]],[i[0],s[1],i[2]],[s[0],s[1],i[2]],[i[0],i[1],s[2]],[s[0],i[1],s[2]],[i[0],s[1],s[2]],[s[0],s[1],s[2]]];let o=!1,n=!1;for(const e of r){const i=t.dist+h.dotVec3(t.dir,e);if(i>0&&(o=!0),i<0&&(n=!0),o&&n)return!0}return!1}_buildLines(e){for(const t in e)for(let i=0;i<e[t].length;i++){const s=e[t][i];s.length<=0||s.forEach(((e,t)=>{new zt(this.scene,{clippable:!1,geometry:new pe(this.scene,Ee({startPoint:e[0],endPoint:e[1]})),material:new Jt(this.scene,{emissive:[1,0,0]})})}))}}_projectTo2D(e,t){let i;i=Math.abs(t[0])>Math.abs(t[1])?[-t[2],0,t[0]]:[0,t[2],-t[1]],i=h.normalizeVec3(i);const s=h.vec3(t),r=h.cross3Vec3(s,i),o=h.normalizeVec3(r);return[h.dotVec3(e,i),h.dotVec3(e,o)]}_isLoopInside(e,t){const i=e[0][0];let s=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){const o=t[e][0][0],n=t[e][0][1],a=t[r][0][0],l=t[r][0][1];n>i[1]!=l>i[1]&&i[0]<(a-o)*(i[1]-n)/(l-n)+o&&(s=!s)}return s}_convertTo3D(e,t,i){let s,r=t.dir,o=t.pos;s=Math.abs(r[0])>Math.abs(r[1])?[-r[2],0,r[0]]:[0,r[2],-r[1]],s=h.normalizeVec3(s);const n=h.vec3(r),a=h.cross3Vec3(n,s),l=h.normalizeVec3(a),A=e[0],c=e[1],u=[s[0]*A+l[0]*c,s[1]*A+l[1]*c,s[2]*A+l[2]*c],d=h.dotVec3(r,[o[0]-u[0]-i[0],o[1]-u[1]-i[1],o[2]-u[2]-i[2]]);return[u[0]+r[0]*d,u[1]+r[1]*d,u[2]+r[2]*d]}_deletePreviousModels(){for(const e in this._prevIntersectionModelsMap){this._prevIntersectionModelsMap[e].forEach(((t,i)=>{this._dirtyMap[e].get(i)&&(t.forEach((e=>{e.destroy()})),this._prevIntersectionModelsMap[e].delete(i))})),this._prevIntersectionModelsMap[e].size<=0&&delete this._prevIntersectionModelsMap[e]}}_createUVs(e,t,i){const s=t.pos,r=sh;r.set(t.dir),h.normalizeVec3(r);const o=rh,n=[];for(let t=0;t<e.length;t+=3){o[0]=e[t]+i[0],o[1]=e[t+1]+i[1],o[2]=e[t+2]+i[2];const a=h.subVec3(o,s,oh),l=h.dotVec3(a,r);h.subVec3(o,h.mulVec3Scalar(r,l,oh),o);const A=Math.abs(h.dotVec3(r,th))<.999?h.cross3Vec3(r,th,oh):ih,c=h.cross3Vec3(r,A,oh);h.normalizeVec3(c,c);const u=h.subVec3(o,s,o);n.push(h.dotVec3(u,h.normalizeVec3(h.cross3Vec3(c,r,nh))),h.dotVec3(u,c))}return n}destroy(){this._deletePreviousModels(),this._resourcesAllocated&&(this.scene.off(this._onModelLoaded),this.scene.off(this._onModelUnloaded),this.scene.off(this._onSectionPlaneCreated),this.scene.off(this._onTick))}}function ch(e,t){const i={};let s,r;for(let o=0,n=t.length;o<n;o++)s=t[o],r=e.components[s],r?r.isEntity?i[s]=!0:e.warn("pick(): Component is not an Entity: "+s):e.warn("pick(): Component not found: "+s);return i}class hh extends T{get type(){return"Scene"}constructor(e,t={}){super(null,t);const i=t.canvasElement||document.querySelector(`#${t.canvasId}`);if(!(i instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";this._tickifiedFunctions={};const s=!!t.transparent,r=!!t.alphaDepthMask;this._aabbDirty=!0,this._readableGeometry=!!t.readableGeometryEnabled,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 UA(this,{dontClear:!0,canvas:i,spinnerElementId:t.spinnerElementId,transparent:s,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 qA(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;e<s;e++)i.push("cp");return i.push(";"),e=i.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let i=0,s=this.sectionPlanes.length;i<s;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)},this.setNumCachedSectionPlanes=function(t){this._numCachedSectionPlanes=t,e=null},this.getNumCachedSectionPlanes=function(){return this._numCachedSectionPlanes},this.getNumAllocatedSectionPlanes=function(){const e=this.sectionPlanes.length;return e>this._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=h.vec4([0,0,0,0]),t=h.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i<r;i++)s=t[i],e.push("/"),e.push(s.type),e.push("world"===s.space?"w":"v"),s.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t<r;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),s&&s.id===e.id&&(s=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(let t=0,s=this.reflectionMaps.length;t<s;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(let t=0,s=this.lightMaps.length;t<s;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!s)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){s=t;break}}if(s){const e=s.color,i=s.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i,t}return e}},this.input=new $A(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new wc(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new Bc(this,{enabled:t.saoEnabled}),this.crossSections=new xc(this,{}),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,this._markerZOffset=t.markerZOffset,M._addScene(this),this._initDefaults(),this._viewport=new ec(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new bc(this,{id:"default.camera",dontClear:!0}),this._sectionCaps=new Ah(this),new AA(this,{color:[1,1,1],intensity:.7}),new hA(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new hA(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 "+_.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 i=this.types[e.type];i||(i=this.types[t]={}),i[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,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],_.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_capMaterialUpdated(e,t){this._sectionCaps._onCapMaterialUpdated(e,t)}_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)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_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)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_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)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){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}_deRegisterOpacityObject(e){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}_deRegisterOffsetObject(e){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 i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}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}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.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 i=this._passes,s=this._clearEachPass;let r,o;for(r=0;r<i;r++)t.pass=r,this.fire("rendering",t,!0),o=s||0===r,this._renderer.render({pass:r,clear:o,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}compile(){this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1)}_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:(!_.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:(!_.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:(!_.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"]||ve(pe)}get material(){return this.components["default.material"]||new Jt(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new vi(this,{id:"default.xrayMaterial",fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new vi(this,{id:"default.highlightMaterial",fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new vi(this,{id:"default.selectedMaterial",fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new yi(this,{id:"default.edgeMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new Cc(this,{id:"default.pointsMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new Fc(this,{id:"default.linesMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){const e=this.aabb;this._center||(this._center=h.vec3()),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,i=h.MAX_DOUBLE,s=h.MAX_DOUBLE,r=h.MIN_DOUBLE,o=h.MIN_DOUBLE,n=h.MIN_DOUBLE;const a=this._collidables;let l,A=!1;for(const c in a)if(a.hasOwnProperty(c)){if(l=a[c],!1===l.collidable)continue;e=l.aabb,e[0]<t&&(t=e[0]),e[1]<i&&(i=e[1]),e[2]<s&&(s=e[2]),e[3]>r&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1,this._center=null}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 i=e.includeEntities||e.include;i&&(e.includeEntityIds=ch(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=ch(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e);this.error("Scene.snapPick() canvasPos parameter expected")}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,i=e.length;t<i;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,i=e.length;t<i;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,i=e.length;t<i;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(_.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,i=h.MAX_DOUBLE,s=h.MAX_DOUBLE,r=h.MAX_DOUBLE,o=h.MIN_DOUBLE,n=h.MIN_DOUBLE,a=h.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const l=e.aabb;l[0]<i&&(i=l[0]),l[1]<s&&(s=l[1]),l[2]<r&&(r=l[2]),l[3]>o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=h.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let o=this.objects[r];if(o)i=t(o)||i;else{const e=this.modelIds;for(let s=0,n=e.length;s<n;s++){const n=e[s],a=h.globalizeObjectId(n,r);o=this.objects[a],o&&(i=t(o)||i)}}}return i}tickify(e){const t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;let i,s=0,r=0;const o=function(...e){i=e,r++},n=this.on("tick",(()=>{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this._sectionCaps.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._sectionCaps=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const uh=h.vec4(),dh=h.vec4(),ph=h.vec3(),fh=h.vec3(),mh=h.vec3(),gh=h.vec4(),_h=h.vec4(),vh=h.vec4();class bh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=h.subVec3(e,r.eye,ph);s=h.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,gh),o=h.subVec3(s,r.eye,vh),n=h.mulVec3Scalar(h.normalizeVec3(o),-i,[]);if(r.eye=[r.eye[0]-n[0],r.eye[1]-n[1],r.eye[2]-n[2]],r.look=[r.look[0]-n[0],r.look[1]-n[1],r.look[2]-n[2]],e){const t=h.subVec3(e,r.eye,ph),i=h.lenVec3(t),s=h.mulVec3Scalar(h.normalizeVec3(h.subVec3(r.look,r.eye,fh)),i);r.look=[r.eye[0]+s[0],r.eye[1]+s[1],r.eye[2]+s[2]]}}else if("ortho"===r.projection){const e=this._unproject(t,gh);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,_h),o=h.subVec3(s,e,vh),n=h.mulVec3Scalar(h.normalizeVec3(h.subVec3(r.look,r.eye,ph)),-i,fh),a=h.addVec3(o,n,mh);r.eye=[r.eye[0]-a[0],r.eye[1]-a[1],r.eye[2]-a[2]],r.look=[r.look[0]-a[0],r.look[1]-a[1],r.look[2]-a[2]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=h.dotVec4(n,r)/h.dotVec4(n,o);return i.project.unproject(e,a,uh,dh,t),t}destroy(){}}const yh=h.vec3(),wh=h.vec3(),Bh=h.vec3(),xh=h.vec4(),Ph=h.vec4(),Ch=h.vec4(),Mh=Math.PI-.001;class Fh{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=h.vec3(),this._cameraOffset=h.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=h.vec3(),this._rtcPos=h.vec3(),this._pivotViewPos=h.vec4(),this._pivotProjPos=h.vec4(),this._pivotCanvasPos=h.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=h.vec3();h.decomposeMat4(h.inverseMat4(this._scene.viewer.camera.viewMatrix,h.mat4()),t,h.vec4(),h.vec3());const i=h.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),Ge(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new ge(this._scene,xe({radius:s})),this._pivotSphere=new zt(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){h.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,h.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(Ge(this.getPivotPos(),this._rtcCenter,this._rtcPos),h.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Jt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){const e=this._scene.camera;let t=h.lookAtMat4v(e.eye,e.look,e.up);h.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=h.distVec3(e.eye,i),t=h.inverseMat4(t);const s=h.transformVec3(t,this._cameraOffset),r=h.vec3();if(h.subVec3(e.eye,i,r),h.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=h.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=h.normalizeVec3(h.subVec3(e.look,e.eye,yh)),i=h.cross3Vec3(t,e.worldUp,wh);return h.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(h.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=h.dotVec4(n,r)/h.dotVec4(n,o),l=xh;t.project.unproject(e,a,Ph,Ch,l);const A=h.normalizeVec3(h.subVec3(l,t.eye,yh)),c=h.addVec3(t.eye,h.mulVec3Scalar(A,i,wh),Bh);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s;const o=r<0,n=r>0,a=Math.abs(this._polar-.001)<.005,l=Math.abs(this._polar-Mh)<.005;let A=this._polar+.01*r;A=a&&o?.001:l&&n?Mh:h.clamp(A,.001,Mh),this._polar=A;const c=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=c[1];c[1]=c[2],c[2]=e}const u=h.lenVec3(h.subVec3(i.look,i.eye,h.vec3())),d=this.getPivotPos();h.addVec3(c,d);let p=h.lookAtMat4v(c,d,i.worldUp);p=h.inverseMat4(p);const f=h.transformVec3(p,this._cameraOffset);p[12]-=f[0],p[13]-=f[1],p[14]-=f[2];const m=[p[8],p[9],p[10]];i.eye=[p[12],p[13],p[14]],h.subVec3(i.eye,h.mulVec3Scalar(m,u),i.look),i.up=[p[4],p[5],p[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Eh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=h.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new IA;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Ih=h.vec2();class Th{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a,l,A,c=0,u=0,d=0,p=0,f=!1;const m=h.vec3();let g=!0;const _=this._scene.canvas.canvas,v=[];function b(e=!0){c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],d=s.pointerCanvasPos[0],p=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(f=!0,m.set(o.pickResult.worldPos)):f=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!1}),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{v.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{v.splice(0)}),_.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:v[e.input.KEY_SHIFT]||i.planView?(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b()):(a=!0,v[e.input.MOUSE_LEFT_BUTTON]=!0,b(!1));break;case 2:l=!0,v[e.input.MOUSE_MIDDLE_BUTTON]=!0,b();break;case 3:A=!0,v[e.input.MOUSE_RIGHT_BUTTON]=!0,i.panRightClick&&b()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!a&&!l&&!A)return;const o=e.canvas.boundary,d=o[2],p=o[3],g=s.pointerCanvasPos[0],_=s.pointerCanvasPos[1],b=i.planView||n._isKeyDownForAction(n.MOUSE_PAN,v),y=n._isKeyDownForAction(n.MOUSE_ROTATE,v),w=document.pointerLockElement?t.movementX:g-c,B=document.pointerLockElement?t.movementY:_-u;if(b){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(f?h.lenVec3(h.subVec3(m,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*w*i/p,r.panDeltaY+=1.5*B*i/p}else r.panDeltaX+=.5*t.ortho.scale*(w/p),r.panDeltaY+=.5*t.ortho.scale*(B/p)}else y&&(i.planView||(i.firstPerson?(r.rotateDeltaY-=w/d*i.dragRotationRate/2,r.rotateDeltaX+=B/p*(i.dragRotationRate/4)):(r.rotateDeltaY-=w/d*(1.5*i.dragRotationRate),r.rotateDeltaX+=B/p*(1.5*i.dragRotationRate))));c=g,u=_}),_.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:case 2:case 3:a=!1,l=!1,A=!1,v[e.input.MOUSE_LEFT_BUTTON]=!1,v[e.input.MOUSE_MIDDLE_BUTTON]=!1,v[e.input.MOUSE_RIGHT_BUTTON]=!1}}),_.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Ih);const i=Ih[0],s=Ih[1];Math.abs(i-d)<3&&Math.abs(s-p)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Ih,event:e},!0)}_.style.removeProperty("cursor")}}),_.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const y=1/60;let w=null;_.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel&&n._isKeyDownForAction(n.MOUSE_DOLLY,v)))return;const t=performance.now()/1e3;var o=null!==w?t-w:0;w=t,o>.05&&(o=.05),o<y&&(o=y);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const l=a/Math.abs(a);r.dollyDelta+=-l*o*i.mouseWheelDollyRate,g&&(s.followPointerDirty=!0,g=!1)},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const Dh=h.vec3(),Sh=h.vec3(),Rh=h.vec3(),Uh=h.vec3(),Lh=h.vec3(),kh={eye:h.vec3(),look:h.vec3(),up:h.vec3()};class Oh{constructor(e,t,i,s){this._scene=e;const r=t.cameraControl,o=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||c||u))return;const d=e.aabb,p=h.getAABB3Diag(d);h.getAABB3Center(d,Dh);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*h.DEGTORAD)),m=1.1*p;kh.orthoScale=m,n?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldRight,f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):a?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldForward,f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):l?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldRight,-f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):A?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldForward,-f,Sh),Lh)),kh.look.set(Dh),kh.up.set(o.worldUp)):c?(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldUp,f,Sh),Lh)),kh.look.set(Dh),kh.up.set(h.normalizeVec3(h.mulVec3Scalar(o.worldForward,1,Rh),Uh))):u&&(kh.eye.set(h.addVec3(Dh,h.mulVec3Scalar(o.worldUp,-f,Sh),Lh)),kh.look.set(Dh),kh.up.set(h.normalizeVec3(h.mulVec3Scalar(o.worldForward,-1,Rh)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Dh),t.cameraFlight.duration>0?t.cameraFlight.flyTo(kh,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(kh),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Nh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;let l=!1,A=!1;const c=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;h.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=h.vec3(),i=h.vec3();h.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),c=a.hasSubs("hoverOut"),u=a.hasSubs("hoverOff"),d=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||c||u||d||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});c.addEventListener("mousemove",d),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot(),this._lastClickedWorldPos=t.worldPos.slice()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):this._lastClickedWorldPos?n.setPivotPos(this._lastClickedWorldPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),c=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=h.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=h.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Vh{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[];e.canvas.canvas;let a=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{a=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(n[t]=!0))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,t.pivotController.getPivoting()&&t.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{n.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{n.splice(0)}),this._onTick=e.on("tick",(l=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=t.cameraControl,c=l.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=c*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),a&&(s.followPointerDirty=!0,a=!1)}}const h=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),m=A._isKeyDownForAction(A.PAN_DOWN,n),g=(n[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(h||u||d||p||f||m)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),m?r.panDeltaY+=g:f&&(r.panDeltaY+=-g),p?r.panDeltaX+=-g:d&&(r.panDeltaX+=g),u?r.panDeltaZ+=g:h&&(r.panDeltaZ+=-g))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),this._scene.input.off(this._onSceneKeyUp)}}const Qh=h.vec3();class Hh{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController,A=t.cameraControl;let c=1,u=1,d=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--c<=0&&(c=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?d=n.pickResult.worldPos:(u=1,d=null),s.followPointerDirty=!1),d){const t=Math.abs(h.lenVec3(h.subVec3(d,e.camera.eye,Qh)));u=t/i.dollyProximityThreshold}u<i.dollyMinSpeed&&(u=i.dollyMinSpeed)}}else u=1,d=null;const p=r.dollyDelta*u;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&a.getPivoting()?(a.continuePivot(r.rotateDeltaY,r.rotateDeltaX),a.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?o.pitch(-r.rotateDeltaX):o.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?o.yaw(r.rotateDeltaY):o.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t=A._cursors.rotate),Math.abs(r.panDeltaX)<.001&&(r.panDeltaX=0),Math.abs(r.panDeltaY)<.001&&(r.panDeltaY=0),Math.abs(r.panDeltaZ)<.001&&(r.panDeltaZ=0),0!==r.panDeltaX||0!==r.panDeltaY||0!==r.panDeltaZ){const e=h.vec3();let s,n;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){o.xUp?(s=o.eye[0],n=o.look[0]):o.yUp?(s=o.eye[1],n=o.look[1]):o.zUp&&(s=o.eye[2],n=o.look[2]),o.pan(e);const t=o.eye,i=o.look;o.xUp?(t[0]=s,i[0]=n):o.yUp?(t[1]=s,i[1]=n):o.zUp&&(t[2]=s,i[2]=n),o.eye=t,o.look=i}else o.pan(e);t=A._cursors.pan}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==p){if(t=p<0?A._cursors.dollyForward:A._cursors.dollyBackward,i.firstPerson){let e,t;if(i.constrainVertical&&(o.xUp?(e=o.eye[0],t=o.look[0]):o.yUp?(e=o.eye[1],t=o.look[1]):o.zUp&&(e=o.eye[2],t=o.look[2])),i.followPointer){l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p;if(i.constrainVertical){const i=o.eye,s=o.look;o.xUp?(i[0]=e,s[0]=t):o.yUp?(i[1]=e,s[1]=t):o.zUp&&(i[2]=e,s[2]=t),o.eye=i,o.look=s}}else if(i.planView)if(i.followPointer){l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);else if(i.followPointer){l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0)}else o.ortho.scale=o.ortho.scale+p,o.zoom(p);r.dollyDelta*=i.dollyInertia}n.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class Gh{constructor(e,t,i,s,r){this._scene=e;const o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{jh(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(jh(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function jh(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const zh=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Wh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=h.vec2(),l=h.vec2(),A=h.vec2(),c=h.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(zh(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length<r.length;)u.push(h.vec2());for(let e=0,t=r.length;e<t;++e)zh(r[e],u[e]);p=r.length}),d.addEventListener("touchend",this._canvasTouchEndHandler=()=>{n.getPivoting()&&(n.endPivot(),n.hidePivot())}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],m=t.touches;if(t.touches.length===p){if(1===p){zh(m[0],l),h.subVec2(l,u[0],c);const t=c[0],o=c[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=m[0],n=m[1];zh(t,l),zh(n,A);const a=h.geometricMeanVec2(u[0],u[1]),c=h.geometricMeanVec2(l,A),p=h.vec2();h.subVec2(a,c,p);const f=p[0],g=p[1],_=e.camera,v=h.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(h.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(h.lenVec3(h.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=g*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(g/d)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<p;++e)zh(m[e],u[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}const Xh=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Kh{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.cameraControl;let a;const l=[],A=new Float32Array(2);let c=-1,u=-1;const d=this._scene.canvas.canvas,p=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;h.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){c=a,Xh(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,h=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{i.active&&i.pointerEnabled&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(h)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else c=-1;for(;l.length<r.length;)l.push(new Float32Array(2));for(let e=0,t=r.length;e<t;++e)Xh(r[e],l[e]);l.length=r.length},{passive:!0}),d.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&c>-1&&t-c<150&&(u>-1&&c-u<325?(Xh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):h.distVec2(l[0],A)<4&&(Xh(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),c=-1),l.length=r.length;for(let e=0,t=r.length;e<t;++e)l[e][0]=r[e].pageX,l[e][1]=r[e].pageY},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class Zh extends T{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this.MOUSE_PAN=18,this.MOUSE_ROTATE=19,this.MOUSE_DOLLY=20,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:h.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:h.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Eh(this,this._configs),pivotController:new Fh(i,this._configs),panController:new bh(i),cameraFlight:new q(this,{duration:.5})},this._handlers=[new Gh(this.scene,this._controllers,this._configs,this._states,this._updates),new Wh(this.scene,this._controllers,this._configs,this._states,this._updates),new Th(this.scene,this._controllers,this._configs,this._states,this._updates),new Oh(this.scene,this._controllers,this._configs,this._states,this._updates),new Nh(this.scene,this._controllers,this._configs,this._states,this._updates),new Kh(this.scene,this._controllers,this._configs,this._states,this._updates),new Vh(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cursors={dollyForward:"zoom-in",dollyBackward:"zoom-out",rotate:"grabbing",pan:"move"},this._cameraUpdater=new Hh(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_areAllKeysDown(e,t){if(!t||t.length<=0)return!0;if(!e)return!1;for(let i=0,s=t.length;i<s;i++){if(!e[t[i]])return!1}return!0}_isAnyOtherKeyDown(e,t){for(let i=0,s=e.length;i<s;i++)if(e[i])if(Array.isArray(t)){if(t.indexOf(i)<0)return!0}else if(i!==t)return!0;return!1}_isMouseAction(e){switch(e){case this.MOUSE_ROTATE:case this.MOUSE_DOLLY:case this.MOUSE_PAN:return!0;default:return!1}}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;if(0===i.length&&this._isMouseAction(e))return!0;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e<s;e++){const s=i[e];if(Array.isArray(s)){if(this._areAllKeysDown(t,s)&&!this._isAnyOtherKeyDown(t,s))return!0}else if(t[s]&&!this._isAnyOtherKeyDown(t,s))return!0}return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}get active(){return this._configs.active}set snapToVertex(e){this._configs.snapToVertex=!!e}get snapToVertex(){return this._configs.snapToVertex}set snapToEdge(e){this._configs.snapToEdge=!!e}get snapToEdge(){return this._configs.snapToEdge}set snapRadius(e){e=e||30,this._configs.snapRadius=e}get snapRadius(){return this._configs.snapRadius}set keyboardEnabledOnlyIfMouseover(e){this._configs.keyboardEnabledOnlyIfMouseover=!!e}get keyboardEnabledOnlyIfMouseover(){return this._configs.keyboardEnabledOnlyIfMouseover}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}setCursorStyle(e,t){Object.prototype.hasOwnProperty.call(this._cursors,e)?this._cursors={...this._cursors,[e]:t}:console.warn(`Action '${e}' is not valid for cursor styles.`)}getCursorStyle(e){return this._cursors[e]||null}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e;const t=this._keyMap[this.MOUSE_PAN];if(t&&t.length>0){const e=this.scene.input;for(let i=0,s=t.length;i<s;i++)this._configs.panRightClick&&t[i]===e.MOUSE_MIDDLE_BUTTON?this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_RIGHT_BUTTON:this._configs.panRightClick||t[i]!==e.MOUSE_RIGHT_BUTTON||(this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_MIDDLE_BUTTON)}}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}enablePivotSphere(e={}){this._controllers.pivotController.enablePivotSphere(e)}disablePivotSphere(){this._controllers.pivotController.disablePivotSphere()}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}set doubleClickTimeFrame(e){this._configs.doubleClickTimeFrame=null!=e?e:250}get doubleClickTimeFrame(){return this._configs.doubleClickTimeFrame}set zoomOnMouseWheel(e){this._configs.zoomOnMouseWheel=!!e}get zoomOnMouseWheel(){return this._configs.zoomOnMouseWheel}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class Jh{constructor(e,t,i,s,r){this.name=e,this.type=i,this.value=t,this.valueType=s,this.description=r}}class Yh{constructor(e){if(this.id=e.id,this.originalSystemId=e.originalSystemId,this.metaModels=[],this.name=e.name,this.type=e.type,this.properties=[],e.properties){const t=e.properties;for(let e=0,i=t.length;e<i;e++){const i=t[e];Number.isInteger(i)?this.properties.push(i):this.properties.push(new Jh(i.name,i.value,i.type,i.valueType,i.description))}}}}class qh{constructor(e){this.metaModels=[],this.id=e.id,this.parentId=e.parentId,this.parent=null,this.originalSystemId=e.originalSystemId,this.name=e.name,this.type=e.type,this.propertySetIds=e.propertySetIds,this.propertySets=[],this.attributes=e.attributes||{},void 0!==e.external&&null!==e.external&&(this.external=e.external)}get metaModel(){return 1==this.metaModels.length?this.metaModels[0]:null}getObjectIDsInSubtree(){const e=[];return function t(i){if(!i)return;e.push(i.id);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this),e}withMetaObjectsInSubtree(e){!function t(i){if(!i)return;e(i);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=e[i];const r=[];return function e(i){if(!i)return;t[i.type]&&r.push(i.id);const s=i.children;if(s)for(var o=0,n=s.length;o<n;o++)e(s[o])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class $h{constructor(e){this.id=e.id,this.projectId=e.projectId,this.revisionId=e.revisionId,this.author=e.author,this.createdAt=e.createdAt,this.creatingApplication=e.creatingApplication,this.schema=e.schema,this.metaScene=e.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects={},this.graph=e.graph||{},this.metaScene.metaModels[this.id]=this,this._propertyLookup=[],this.finalized=!1}get rootMetaObject(){return 1===this.rootMetaObjects.length?this.rootMetaObjects[0]:null}loadData(e,t={}){if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);const i=this.metaScene,s=e.properties;if(s)for(let e=0,t=s.length;e<t;e++)this._propertyLookup.push(s[e]);if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.properties||(s.properties=[]);let r=i.propertySets[s.id];r||(r=new Yh({id:s.id,originalSystemId:s.originalSystemId||s.id,type:s.type,name:s.name,properties:s.properties}),i.propertySets[r.id]=r),r.metaModels.push(this),this.propertySets.push(r)}if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t],r=s.id;let o=i.metaObjects[r];if(!o){const e=s.type,t=s.originalSystemId,i=s.propertySets||s.propertySetIds;o=new qh({id:r,originalSystemId:t,parentId:s.parent,type:e,name:s.name,attributes:s.attributes,propertySetIds:i,external:s.external}),this.metaScene.metaObjects[r]=o,o.metaModels=[]}this.metaObjects[r]=o,s.parent||(this.rootMetaObjects.push(o),i.rootMetaObjects[r]=o),o.metaModels.push(this)}}_decompressProperties(e,t){const i=[];for(let s=0,r=t.length;s<r;s++){const r=t[s];if(Number.isInteger(r)){const o=e[r];o?t[s]=o:i.push(r)}}i.length>0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t<s;t++){const s=i.propertySetIds[t],r=e.propertySets[s];i.propertySets.push(r)}}for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.parentId){const t=e.metaObjects[i.parentId];t&&(i.parent=t,(t.children||(t.children=[])).push(i))}}for(let t in e.metaObjects){e.metaObjects[t].metaModels=[]}for(let t in e.metaModels){const i=e.metaModels[t];for(let e in i.metaObjects){i.metaObjects[e].metaModels.push(i)}}e.metaObjectsByType={};for(let t in e.metaObjects){const i=e.metaObjects[t],s=i.type;(e.metaObjectsByType[s]||(e.metaObjectsByType[s]={}))[t]=i}if(this.propertySets)for(let e=0,t=this.propertySets.length;e<t;e++){const t=this.propertySets[e];this._decompressProperties(this._propertyLookup,t.properties)}this._propertyLookup=[],this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}getJSON(){const e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]},t=Object.values(this.metaObjects);for(let i=0,s=t.length;i<s;i++){const s=t[i],r={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name};s.parent&&(r.parent=s.parent.id),s.attributes&&(r.attributes=s.attributes),s.propertySetIds&&(r.propertySetIds=s.propertySetIds),e.metaObjects.push(r)}for(let t=0,i=this.propertySets.length;t<i;t++){const i=this.propertySets[t],s={id:i.id,originalSystemId:i.originalSystemId,extId:i.extId,type:i.type,name:i.name,propertyies:[]};for(let e=0,t=i.properties.length;e<t;e++){const t=i.properties[e],r={id:t.id,description:t.description,type:t.type,name:t.name,value:t.value,valueType:t.valueType};s.properties.push(r)}e.propertySets.push(s)}return e}_globalizeIDs(e,t){const i=!!t.globalizeObjectIds;if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t];if(s.originalSystemId=s.id,s.parent&&(s.originalParentSystemId=s.parent),i&&(s.id=h.globalizeObjectId(this.id,s.id),s.parent&&(s.parent=h.globalizeObjectId(this.id,s.parent))),i){const e=s.propertySetIds;if(e){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(h.globalizeObjectId(this.id,e[i]));s.propertySetIds=t,s.originalSystemPropertySetIds=e}}else s.originalSystemPropertySetIds=s.propertySetIds}if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.originalSystemId=s.id,i&&(s.id=h.globalizeObjectId(this.id,s.id))}}}class eu{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}createMetaModel(e,t,i={}){const s=new $h({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return s.loadData(t),s.finalize(),s}destroyMetaModel(e){const t=this.metaModels[e];if(t){if(t.propertySets)for(let i=0,s=t.propertySets.length;i<s;i++){const s=t.propertySets[i];if(1===s.metaModels.length&&s.metaModels[0].id===e)delete this.propertySets[s.id];else{const t=[];for(let i=0,r=s.metaModels.length;i<r;i++)s.metaModels[i].id!==e&&t.push(s.metaModels[i]);s.metaModels=t}}if(t.metaObjects)for(let i in t.metaObjects){const s=t.metaObjects[i];1===s.metaModels.length&&s.metaModels[0].id===e?(delete this.metaObjects[i],s.parent||delete this.rootMetaObjects[i]):s.metaModels=s.metaModels.filter((t=>t.id!==e))}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.children&&(t.children=[]),t.propertySets&&(t.propertySets=[]),t.propertySetIds)for(let e=0,i=t.propertySetIds.length;e<i;e++){const i=t.propertySetIds[e],s=this.propertySets[i];t.propertySets.push(s)}}this.metaObjectsByType={};for(let e in this.metaObjects){const t=this.metaObjects[e],i=t.type;t.children&&(t.children=null),(this.metaObjectsByType[i]||(this.metaObjectsByType[i]={}))[e]=t}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.parentId){const e=this.metaObjects[t.parentId];e&&(t.parent=e,(e.children||(e.children=[])).push(t))}}delete this.metaModels[e];for(let e in this.metaObjects){this.metaObjects[e].metaModels=[]}for(let e in this.metaModels){const t=this.metaModels[e];for(let e in t.metaObjects){t.metaObjects[e].metaModels.push(t)}}this.fire("metaModelDestroyed",e)}}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,i){const s=[],r=this.metaObjects[e],o=t&&t.length>0?tu(t):null,n=i&&i.length>0?tu(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r<l;r++)a(i[r])};return a(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function tu(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}
24
24
  /*!
25
25
  * html2canvas 1.4.1 <https://html2canvas.hertzen.com>
26
26
  * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>